简体   繁体   中英

How to Stub out Warden/Devise with Rspec in Capybara test

I want to stub out a logged in user (with Devise/Warden) using rspec mocks in a Capybara test suite in my Rails app. This would save a ton of time, and would mean that my test suite can/will be run regularly.

Previously I was able to do this using authlogic by stubbing out my session model with some code like this:

def login(user)
  user_session = mock_model(UserSession, {:user => user})
  UserSession.stub(:find).and_return(user_session)
end

Now that i'm using Devise, i no longer have access to a UserSession object. And since i'm using capybara to test my code, i don't have direct access to the request object to use devise's built in sign_in test helper.

My question is: how can I simulate a logged in user with capybara, devise, and spec mocks without requiring every scenario with a logged in user to first go to the sign up path, fill in the form, submit, wait for response, and then go to the desired page?

Warden comes with built in test helpers. It allows you to login without having to use the UI in your cucumber tests. Just add the files below into your project.

# features/support/warden.rb

Warden.test_mode!
World Warden::Test::Helpers
After { Warden.test_reset! }

# features/step_definitions/user_steps.rb

Given /^I am logged in as a user$/ do
  @current_user = User.create!(:username => 'user', :password => 'password')
  login_as(@current_user, :scope => :user)
end

Use Wardens.test_mode! with Capybara

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