0

I'm using system tests to verify that the following flow works as expected for a user:

  1. Sign up in a form
  2. Get signed in
  3. Visit account page
  4. Update account information

However, I'm getting an error after user creation:

Puma caught this error: Couldn't find User with 'id'=16 (ActiveRecord::RecordNotFound)
/Me/MyComputer/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/activerecord-5.1.4/lib/active_record/core.rb:189:in `find'
/Me/MyComputer/Documents/my_app/app/controllers/application_controller.rb:30:in `current_user'

The error is pointing to the code that sets current_user in application_controller:

def current_user
  if session[:user_id]
    @current_user ||= User.find(session[:user_id])
  end
end

Is my assumption correct that it's not possible to access session in tests? And if so - how can I then set current_user so I can test my scenario above? If not so - what could be causing the error?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • Possible duplicate of [Testing Rails Controller with Session](https://stackoverflow.com/questions/24365505/testing-rails-controller-with-session) – Manishh Dec 02 '17 at 04:22
  • 1
    In a rails system test your application should be able to access the session, your test code however cannot. In your case I assume `current_user` is being called from the application code, not from test code. In that case the most common reason for DB weirdness is that your Puma instance is running in clustered mode (separate process) rather than the required single mode (same process just a different thread). What output does Puma produce when you start up your tests? It might also help if you show your test code, so we can see exactly what you're doing. – Thomas Walpole Dec 02 '17 at 05:00
  • Additionally, if you're trying to shortcut the login process and set the current user from your tests, some authentication gems provide tests modes to enable that. Which, if any, authentication gem are you using? – Thomas Walpole Dec 02 '17 at 05:03
  • Thank you very much!! Running Puma in single mode solved it :) – Fellow Stranger Dec 04 '17 at 00:56
  • @FellowStranger Added as an answer so you can accept and mark the question answered – Thomas Walpole Dec 04 '17 at 16:43

1 Answers1

1

In a rails system test your application should be able to access the session, your test code however cannot. In your case I assume current_user is being called from the application code, not from test code. In that case the most common reason for DB weirdness is that your Puma instance is running in clustered mode (separate process) rather than the required single mode (same process just a different thread). Check the output of Puma when running tests and make sure it states "single mode" - If not you'll need to adjust the configuration of Puma in the test environment to use 0 processes and 1 or more threads (as needed for your testing)

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78