我对使用rspec很陌生,并且正在尝试为我的 Controller 编写测试。我有这个 Controller (我正在使用 Mocha 进行 stub ):

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])。测试此操作的最佳方法是什么,或者如果我走对了,我将如何正确处理我的模型调用?

最佳答案

好的,删除以前的答案是错误的。

首先:您正在 stub find而不是find_by_id。尽管您不需要使用find_by_id,因为这是find的默认设置。所以用find
第二:before :each排序将在 stub 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

关于ruby-on-rails - RSpec关于 Controller 和 stub ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3167579/

10-13 09:37