我对使用 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])
为“应该分配卡”测试存根这条线。测试此操作的最佳方法是什么,或者如果我在正确的轨道上,我将如何正确地存根我的模型调用?