【问题标题】:Assign variable in rspec controller test在 rspec 控制器测试中分配变量
【发布时间】:2013-03-17 19:48:46
【问题描述】:

我有一个 rspec 测试,我需要在其中测试我的控制器。

it "renders the #show view" do
  get :show, id: FactoryGirl.create(:quiz)
  @facebook_profile = FactoryGirl.create(:facebook_profile)
  response.should render_template :show
end

facebook_profile 对象有一个 user_q1 列,所以@facebook_profile.user_q1 给出了一个有效的结果。

在我的测验控制器中:

@user_q1 = @facebook_profile.user_q1

这在手动测试中效果很好,但在 rspec 中,我得到了结果:

undefined method `user_q1' for nil:NilClass

我怀疑问题出在这里,在控制器中我的 show 方法的第一行:

@facebook_profile = FacebookProfile.find_by_facebook_id(session[:facebook_profile_id])

我的会话控制器中有一个变量(尽管不是任何模型中的列),我称之为 facebook_profile_id。然后我在我的测验控制器的上述代码行中调用此变量。我认为我的规范无法定义@facebook_profile,因为它不知道 facebook_profile_id。显然,仅仅定义“@facebook_profile = FactoryGirl”(就像我上面所说的那样)是行不通的。

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec controller factory-bot


    【解决方案1】:

    你应该这样做:

    let(:fb_profile) { FactoryGirl.create(:facebook_profile) }
    let(:quiz) { FactoryGirl.create(:quiz) )
    
    it "renders the #show view" do
      FacebookProfile.should_receive(:find_by_facebook_id).and_return fb_profile
      get :show, id: quiz.id
      response.should render_template :show 
    end
    

    实际上你不需要在 db 中创建对象,但这是另一个争论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多