7

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?

user3574603
  • 3,364
  • 3
  • 24
  • 59
  • Thinking about this on the move: I think the problem is that the user is not confirmed. – user3574603 Nov 18 '17 at 14:22
  • Duplicate: https://stackoverflow.com/questions/43993465/how-do-i-log-in-a-user-with-devise-for-rails-controller-integration-unit-tests?rq=1 – domi91c Nov 18 '17 at 15:37
  • Possible duplicate of [How do I log in a user with Devise for Rails controller/integration unit tests?](https://stackoverflow.com/questions/43993465/how-do-i-log-in-a-user-with-devise-for-rails-controller-integration-unit-tests) – domi91c Nov 18 '17 at 15:37

1 Answers1

8

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 %>
user3574603
  • 3,364
  • 3
  • 24
  • 59