RSpec控制器和Stubbing

时间:2010-07-02 16:47:16

标签: ruby-on-rails unit-testing rspec mocha stubbing

我是使用rspec的新手,我正在尝试为我的控制器编写测试。我有这个控制器(我使用mocha进行存根):

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

“应该分配卡集”测试通过,但我无法弄清楚如何正确地将此行@card = @cardset.cards.find_by_id(params[:id])存入“应分配卡”测试。测试此操作的最佳方法是什么,或者如果我在正确的轨道上,我将如何正确地存根模型调用?

2 个答案:

答案 0 :(得分:0)

好的,删除了之前的错误答案。

首先:你是find而不是find_by_id。虽然您不需要使用find_by_id,因为这是find的默认值。所以请使用find

第二:before :each排序将在你的存根get :show之前调用Cardset

第三:检查你的test.log并确保你没有被重定向。在require_user被设置之前,您的current_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

答案 1 :(得分:0)

我最终在寻找这些

的存根
Cardset.stubs(:find_by_id).returns(@cardset)
@cardset.cards.stubs(:find_by_id).returns(@card)