Read more

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

Arne Hartherz
December 02, 2015Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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')
Posted by Arne Hartherz to makandra dev (2015-12-02 14:31)