6

For nearly every integration test, a user has to be signed into Devise. This takes a lot of time, so I wondered whether there's a way to set up the user session without having to visit the login page, enter details, and press the login button.

Maybe there's a helper method built into Devise that immediately signs a given user in?

Thanks a lot for help.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152

1 Answers1

16

In the header of your spec file, insert include Warden::Test::Helpers and Warden.test_mode!, like this:

require 'spec_helper'

include Warden::Test::Helpers
Warden.test_mode!

describe "AuthenticationPages" do

let(:user) { FactoryGirl.create(:user) }

before { login_as(user, scope: :user }
...

In above code, i used FactoryGirl to create an user. You can use other ways you like to create user. Then I login user by using method login_as . Then you can run any test and you can sure user has loged in. I think this is what you want, hope this help. You can see more details here Test with capybara.

EDIT

To make sure this works correctly you will need to reset warden after each test you can do this by calling

Warden.test_reset! 

If for some reason you need to log out a logged in test user, you can use Warden's logout helper.

logout(:user)
Rimian
  • 36,864
  • 16
  • 117
  • 117
Thanh
  • 8,219
  • 5
  • 33
  • 56
  • Thanks a lot, this is great. However, I don't want to put it into every *_spec.rb file. I have a module `ValidUserRequestHelper` which is included into my request specs using `RSpec.configure do |c| { c.include ValidUserRequestHelper, :type => :request }`, and I tried putting `include Warden::Test::Helpers` and `Warden.test_mode!` into there, but this doesn't seem to work. Any idea? – Joshua Muheim Nov 01 '12 at 12:27
  • Ooops, Spork didn't see my changes... After restarting it, it's working now. :-) Thanks. – Joshua Muheim Nov 01 '12 at 12:32