2010-07-02 55 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