简体   繁体   中英

Why doesn't this RSpec stub work?

i have created an rspec test like :

    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

Then, i wrote the controller part :

# 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 

And the model part :

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

I would expect that the test succeeds, now but i get :

  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

Do i have a mistake somewhere ?

THE MACRO FOR LOGIN USER :

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

Untested:

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

Your mock doesn't do anything... perhaps you meant to use it somewhere?

I personally dislike mocking in this case and feel it's obfuscation. If you are using Devise you could use their test helpers to sign in as a user .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM