Rails: How do I login a Devise user in an integration test?

Viewed 2193

I am trying to test that a logged in user can access the admin page.

I have a user set up in the fixtures:

user_one:
  email: user_one@test.com
  encrypted_password: <%= User.new.send(:password_digest, 'password') %>

In the test, I log in and navigate to the admin page. But the test fails with a redirect.

class AdminTestLoggedIn < ActionDispatch::IntegrationTest
  test "Log in" do
    post user_session_path, params: {user: {
      email:    users(:user_one).email,
      password: "password"
    }}

    get admin_path
    assert_response :success
  end
end

I can see that the redirect points back to the login page:

  test "Log in" do
    ...

    assert_redirected_to new_user_session_path
  end

So, it looks like I haven't logged in. Where have I gone wrong? My guess is that I haven't handle the password encryption properly. If that's the case, how should it be done?

1 Answers

My initial test failed because I'd set users to :confirmable but user_one had no :confirmed_at date. Without confirmation, the user could not log in and therefore admin_path was redirecting.

The fix was to set :confirmed_at in users.yml:

user_one:
  email: user_one@test.com
  encrypted_password: <%= User.new.send(:password_digest, 'password') %>
  confirmed_at: <%= Time.now %>
Related