为什么这个RSpec存根不起作用?

时间:2011-03-10 04:07:52

标签: ruby-on-rails rspec

我创建了一个类似的rspec测试:

    it "should redirect to '/tavern' with an error if user already has a tavern quest" do
        user = mock('User')
        user.stub(:has_tavern_quest).and_return(true)
        post :new_quest, :quest_type => 3
        flash[:error].should_not be_nil
        response.should redirect_to tavern_path
    end

然后,我写了控制器部分:

# check if user already has a tavern quest
if current_user.has_tavern_quest?
    flash[:error] = 'You already have a quest to finish !'
    redirect_to tavern_path and return 
end 

模型部分:

  def has_tavern_quest?
    TavernQuest.exists?(self.id)
  end   

我希望测试成功,但现在我得到了:

  1) TavernController POST '/quest/' to get a new quest of quest_type == 3 should redirect to '/tavern' with an error if user already has a tavern quest
     Failure/Error: flash[:error].should_not be_nil
       expected: not nil
            got: nil
     # ./spec/controllers/tavern_controller_spec.rb:29

我在某个地方有错误吗?

登录用户的宏:

module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = :user
      @user = Factory.create(:user)
      sign_in @user
    end
  end
end

2 个答案:

答案 0 :(得分:2)

未测试:

it "should redirect to '/tavern' with an error if user already has a tavern quest" do
  controller.stub_chain(:current_user,:has_tavern_quest?).and_return(true)
  post :new_quest, :quest_type => 3
  flash[:error].should_not be_nil
  response.should redirect_to tavern_path
end

答案 1 :(得分:1)

你的模拟没有做任何事情......也许你打算在某个地方使用它?

我个人不喜欢在这种情况下嘲笑并觉得这是混淆。如果您使用的是Devise,则可以their test helpers使用sign in as a user