Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: [email protected]
  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?

like image 919
user3574603 Avatar asked Nov 18 '17 12:11

user3574603


People also ask

What are integration tests in rails?

Integration tests are used to test how various parts of our application interact. They are generally used to test important workflows within our application. For creating Rails integration tests, we use the test/integration directory for our application. Rails provides a generator to create an integration test skeleton for us.

How do I create a login system in rails?

I already have one built, but if you are looking to just play around or create your own new project for whatever reason, you can do so by using the rails new <app-name> command. For our login system, the goal is to have a Sign Up page where users can create an account and a Login page that will allow them to log into their account.

How do I run system tests in rails?

System tests use Capybara under the hood. For creating Rails system tests, you use the test/system directory in your application. Rails provides a generator to create a system test skeleton for you. By default, system tests are run with the Selenium driver, using the Chrome browser, and a screen size of 1400x1400.

What is this Ruby on rails guide for?

The guide is a short tutorial on how to create a Ruby on rails application, add some extra fields to the model. Programming since 2008. Authentication. You don’t always want your users to have faceless sessions that open your application without leaving any trace.


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: [email protected]
  encrypted_password: <%= User.new.send(:password_digest, 'password') %>
  confirmed_at: <%= Time.now %>
like image 66
user3574603 Avatar answered Nov 14 '22 23:11

user3574603