2010-07-02 53 views
1

我很新使用rspec,並且正在嘗試爲我的控制器編寫我的測試。我有這個控制器(我用摩卡的磕碰):在控制器和stubbing上的RSpec

class CardsController < ApplicationController 
    before_filter :require_user 

    def show 
    @cardset = current_user.cardsets.find_by_id(params[:cardset_id]) 

    if @cardset.nil? 
     flash[:notice] = "That card doesn't exist. Try again." 
     redirect_to(cardsets_path) 
    else 
     @card = @cardset.cards.find_by_id(params[:id]) 
    end 
    end 
end 

我試圖測試像這樣的東西這個動作:

describe CardsController, "for a logged in user" do 
    before(:each) do 
    @cardset = Factory(:cardset) 
    profile = @cardset.profile 
    controller.stub!(:current_user).and_return(profile) 
    end 

    context "and created card" do 
    before(:each) do 
     @card = Factory(:card) 
    end 

    context "with get to show" do 
     before(:each) do 
     get :show, :cardset_id => @cardset.id, :id => @card.id 
     end 

     context "with valid cardset" do 
     before(:each) do 
      Cardset.any_instance.stubs(:find).returns(@cardset) 
     end 

     it "should assign card" do 
      assigns[:card].should_not be_nil 
     end 

     it "should assign cardset" do 
      assigns[:cardset].should_not be_nil 
     end 

     end 
    end 
    end 
end 

的「應指派cardset」測試通過,但我無法弄清楚如何正確存根這條線@card = @cardset.cards.find_by_id(params[:id])爲「應分配卡」測試。測試此操作的最佳方式是什麼,或者如果我在正確的軌道上,我將如何正確存根模型調用?

回答

0

,我結束了尋找這些地方

Cardset.stubs(:find_by_id).returns(@cardset) 
@cardset.cards.stubs(:find_by_id).returns(@card) 
+0

'stubs'方法在RSpec 2.8中不適用於我,但'stub'是。任何有此問題的人都可以嘗試此修訂:'Cardset.stub(:find).and_return(@cardset)'。 – evanrmurphy 2012-03-15 17:43:28

0

好吧,刪除以前的答案是錯的。

第一:你是沾了find而不是find_by_id。儘管您不需要使用find_by_id,因爲這是find的默認值。因此,使用find

第二:before :each訂貨會調用之前的get :show你存根Cardset

三:檢查您的test.log中,並確保你沒有得到重定向。在current_user被設置之前,您的require_user操作可能會導致重定向。

class CardsController < ApplicationController 
    ... 
    @card = @cardset.cards.find(params[:id]) 
    ... 
end 

describe CardsController, "for a logged in user" do 
    before(:each) do 
    @cardset = Factory(:cardset) 
    profile = @cardset.profile 
    controller.stub!(:current_user).and_return(profile) 
    end 

    context "and created card" do 
    before(:each) do 
     @card = Factory(:card) 
    end 

    context "with get to show" do 

     context "with valid cardset" do 
     before(:each) do 
      Cardset.any_instance.stubs(:find).returns(@cardset) 
      get :show, :cardset_id => @cardset.id, :id => @card.id 
     end 

     it "should assign card" do 
      assigns[:card].should_not be_nil 
     end 

     it "should assign cardset" do 
      assigns[:cardset].should_not be_nil 
     end 

     end 
    end 
    end 
end 
+0

好,謝謝,我會檢查這些事情的存根。我使用find_by_id的理由是,當找不到記錄時,返回nil而不是拋出異常,這在這種情況下似乎更容易處理。 – trobrock 2010-07-02 17:41:01

+0

我更新了我的代碼,以顯示此處顯示的內容:http://gist.github.com/461667我仍然遇到了一個失敗的「應該分配卡」測試,雖然我正在通過'before_filter'重定向,但您仍然正確。 – trobrock 2010-07-02 17:56:57