2013-03-17 83 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 

其實你並不需要創建數據庫對象,但這是另一個爭論。