在系统测试中设置current_user

时间:2022-03-04 22:46:50

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

我正在使用系统测试来验证以下流程是否按预期为用户工作:

  1. Sign up in a form
  2. 在表格中注册
  3. Get signed in
  4. 登录
  5. Visit account page
  6. 访问帐户页面
  7. Update account information
  8. 更新帐户信息

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:

该错误指向在application_controller中设置current_user的代码:

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?

我的假设是否正确,在测试中无法访问会话?如果是这样 - 我怎么能设置current_user所以我可以测试上面的场景?如果不是这样 - 可能导致错误的原因是什么?

1 个解决方案

#1


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)

在rails系统测试中,您的应用程序应该能够访问会话,但是您的测试代码却无法访问。在您的情况下,我假设从应用程序代码调用current_user,而不是从测试代码调用。在这种情况下,DB怪异的最常见原因是您的Puma实例在集群模式(单独的进程)而不是所需的单一模式(相同的进程只是一个不同的线程)中运行。运行测试时检查Puma的输出并确保它处于“单一模式” - 如果不是,则需要在测试环境中调整Puma的配置以使用0个进程和1个或多个线程(根据测试需要)

#1


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)

在rails系统测试中,您的应用程序应该能够访问会话,但是您的测试代码却无法访问。在您的情况下,我假设从应用程序代码调用current_user,而不是从测试代码调用。在这种情况下,DB怪异的最常见原因是您的Puma实例在集群模式(单独的进程)而不是所需的单一模式(相同的进程只是一个不同的线程)中运行。运行测试时检查Puma的输出并确保它处于“单一模式” - 如果不是,则需要在测试环境中调整Puma的配置以使用0个进程和1个或多个线程(根据测试需要)