How to login a user in Capybara tests when using Devise

Assuming we are using RSpec & Capybara to write our feature tests and utilizing Devise for authentication, we can login users in our tests like so:

Include Warden test helpers

Create a spec/support/devise.rb file with the following configuration:

RSpec.configure do |config|
  config.include Warden::Test::Helpers
end

Include this support file in spec/rails_helper.rb:

require 'support/devise'

Use the login_as helper method

Now we can use the login_as method to log in any ActiveRecord user like so:

# Create user however you want (e.g. using Factory Bot)
user = FactoryBot.create(:user)
login_as(user)

# Session will now be authenticated
visit root_path

See Devise’s wiki page for more info on testing with Capybara.

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com