Stubbing authentication in request spec
A request spec is a thin wrapper around ActionDispatch::IntegrationTest
, which doesn't work like controller specs (which wrap ActionController::TestCase
). Even though there is a session method available, I don't think it is supported (i.e. it's probably there because a module that gets included for other utilities also includes that method).
I'd recommend logging in by posting to whatever action you use to authenticate users. If you make the password 'password' (for example) for all the User factories, then you can do something like this:
def login(user) post login_path, :login => user.login, :password => 'password' end
Note for Devise users...
BTW, @David Chelimsky's answer may need a little tweaking if you're using Devise. What I'm doing in my integration / requests testing (thanks to this StackOverflow post):
# file: spec/requests_helper.rb
# Rails 6
def login(user)
post user_session_path, params: {
user: {
email: user.email, password: user.password
}
}
follow_redirect!
end
# Rails 5 or older
def login(user)
post_via_redirect user_session_path, 'user[email]' => user.email, 'user[password]' => user.password
end