在系统测试中设置current_user [英] Setting current_user in system tests

查看:186
本文介绍了在系统测试中设置current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  1. 注册表单
  2. 登录
  3. 访问帐户页面
  4. 更新帐户信息

但是,创建用户后出现错误:

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'

错误指向在application_controller中设置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

我的假设是否正确,即无法在测试中访问会话?如果是的话,我该如何设置current_user以便测试上述情况?如果不是这样-可能是什么原因导致错误?

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?

推荐答案

在Rails系统测试中,您的应用程序应该能够访问会话,但是您的测试代码不能.在您的情况下,我假设从应用程序代码而不是测试代码中调用current_user.在这种情况下,数据库异常的最常见原因是您的Puma实例以集群模式(独立进程)运行,而不是所需的单一模式(同一进程只是一个不同的线程)运行.在运行测试时检查Puma的输出,并确保其显示单一模式"-否则,您需要在测试环境中调整Puma的配置以使用0个进程和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)

这篇关于在系统测试中设置current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆