RSpec & Devise: How to sign in users in request specs

You know Show archive.org snapshot that Devise offers RSpec test helpers for controller specs. However, in request specs, they will not work.

Here is a solution for request specs, adapted from the Devise wiki Show archive.org snapshot . We will simply use Warden's test helpers -- you probably already load them for your Cucumber tests.

First, we define sign_in and sign_out methods. These will behave just like those you know from controller specs:

module DeviseRequestSpecHelpers

  include Warden::Test::Helpers

  def sign_in(resource_or_scope, resource = nil)
    resource ||= resource_or_scope
    scope = Devise::Mapping.find_scope!(resource_or_scope)
    login_as(resource, scope: scope)
  end

  def sign_out(resource_or_scope)
    scope = Devise::Mapping.find_scope!(resource_or_scope)
    logout(scope)
  end

end

Finally, load that module for request specs:

RSpec.configure do |config|
  config.include DeviseRequestSpecHelpers, type: :request
end

Done. You can now write request specs like this:

sign_in create(:user, name: 'John Doe')
visit root_path
expect(page).to include('John Doe')
Arne Hartherz Over 8 years ago