Posted over 5 years ago. Visible to the public. Linked content.

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

You know 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. 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')
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
Last edit:
over 3 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