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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With