2013-03-17 51 views
0

我有一个rspec测试,需要测试我的控制器。在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 

我怀疑问题就在这里,在第一线我的显示方法在控制器中:

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

我在会话控制器中有一个变量(虽然不是我称之为facebook_profile_id。然后我在测验控制器的上面这行代码中调用这个变量。我认为我的规范不能定义@facebook_profile,因为它不知道facebook_profile_id。显然只是定义“@facebook_profile = FactoryGirl”(就像我上面所说的)不起作用。

回答

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 

其实你并不需要创建数据库对象,但这是另一个争论。