Posted almost 7 years ago. Visible to the public. Linked content.

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

You know Archive 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 Archive . 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')

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Arne Hartherz
Last edit:
almost 5 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more