我有一个用于记录设备用户的@user实例。这是Devise wiki提出的一个宏:
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = :user
@user = Factory(:user)
sign_in @user
end
end
end
通常,我对存根方法做了不同的事情,但我不明白为什么这个存根不起作用:(注意@user确实已登录,我成功地使用它来测试属性和东西)
@user.stub(:has_tavern_quest?).and_return(true)
似乎存根工作(我用@ user.has_tavern_quest检查应该是真的),但我回来了:
Failure/Error: flash[:error].should == I18n.t('error.has_quest')
expected: "You already have a quest to finish !"
got: nil (using ==)
整个控制器方法是:
quest_type = params[:quest_type]
@quest_minutes = TavernQuest.get_quest_minutes_from_quest_type(quest_type)
flash[:error] = I18n.t('error.invalid_post') and redirect_to tavern_url and return unless [1,2,3,4].include? quest_type.to_i
flash[:error] = I18n.t('error.has_quest') and redirect_to tavern_url and return if current_user.has_tavern_quest?
flash[:error] = I18n.t('error.no_adv_points') and redirect_to tavern_url and return if current_user.adventure_points < @quest_minutes
current_user.reduce_adventure_points(@quest_minutes.to_i)
TavernQuest.create(:user_id => current_user.id, :start_time => Time.now, :end_time => Time.now + @quest_minutes.minutes,
:duration => @quest_minutes, :quest_type => quest_type)
redirect_to tavern_url
端
整个规范是:
it "should redirect to '/tavern' with an error if user already has a tavern quest" do
@user.stub(:has_tavern_quest?).and_return(true)
post :create, :quest_type => 3
flash[:error].should == I18n.t('error.has_quest')
response.should redirect_to tavern_url
end
任何人都知道为什么以及使它运作的方式是什么?
答案 0 :(得分:3)
解决了:
def login_user
before(:each) do
@user = Factory(:user)
controller.stub(:current_user) { @user }
sign_in @user
end
end