ruby on rails 3-如何使用RSpec存根控制器实例变量



new_controller_spec.rb

require 'spec_helper'
describe NewController do
  describe 'actions' do 
    describe 'POST /franchise_opportunities' do  
     it 'renders v3/franchise_opportunities when domain id 5' do
        domain = double(Domain, mrdeliverycom?: true)
        controller.instance_variable_set(:@domain, domain)
        post :franchise_opportunities, name: 'v'
        response.should render_template('v3/franchise_opportunities')
      end
    end
  end
end

new_controller.rb

# -*- encoding : utf-8 -*-
class NewController < ApplicationController
 before_filter { @domain = ... }
 def franchise_opportunities
    t = Logger.new(STDOUT)
    t.debug '=============================================='
    t.debug @domain
    t.debug @domain.mrdeliverycom?
    t.debug '=============================================='
    render :layout=>'v3', :template=>'v3/franchise_opportunities' and return if @domain && @domain.mrdeliverycom?
    @errors={}
    @post = params.clone
    ...
 end
end

日志

    ==============================================
#<Domain id: 1, name: "hettingersawayn.org", email: "alfonso.carroll@eichmanngrady.name", created_at: "2015-06-06 13:11:49", updated_at: "2015-06-06 13:11:49", domain_name: "ziemann.info8732", logo: nil, favicon: nil, slogan: nil, meta_title: nil, meta_keywords: nil, meta_description: nil, about_us: nil, smtp_server: "smtp.gmail.com", smtp_port: "587", smtp_username: nil, smtp_password: nil, smtp_authentication: "plain", smtp_tls: true, background: nil, source: "web", mobile_logo: nil, show_chef: false, ios_icon: nil, intro_text: nil>
    nil
    ==============================================

似乎@domain变量是在spec方法中设置的,而不是在控制器的before_filter中设置的@domain可变。

事实上,实例变量被设置为您在示例中提供的值,但这发生在before_filter执行之前,因此它最终会被再次设置。

您可以将初始化从before_filter移到控制器和存根中的一个方法中:

before_filter { @domain = get_domain }
...
protected
def get_domain
  ...
end
...
expect(controller).to receive(:get_domain).and_return("stubbed value")

相关内容

  • 没有找到相关文章

最新更新