我很新使用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])
爲「應分配卡」測試。測試此操作的最佳方式是什麼,或者如果我在正確的軌道上,我將如何正確存根模型調用?
'stubs'方法在RSpec 2.8中不適用於我,但'stub'是。任何有此問題的人都可以嘗試此修訂:'Cardset.stub(:find).and_return(@cardset)'。 – evanrmurphy 2012-03-15 17:43:28