模型测试中未定义的局部变量或方法“会话”

时间:2021-02-11 23:53:51

I'm creating a Ruby on Rails application, and am trying to run a test involving my User model to see if the "Remember me" feature works. I'm using Rails' inbuilt cookies hash to store the cookies, and the session hash to store the current session. I've run various tests (integration, model, and controller) where I use the session variable, but for some reason in this particular case it isn't being recognized.

我正在创建一个Ruby on Rails应用程序,并且正在尝试运行涉及我的User模型的测试,以查看“记住我”功能是否有效。我使用Rails的内置cookie散列来存储cookie,并使用会话散列来存储当前会话。我运行各种测试(集成,模型和控制器),我使用会话变量,但由于某种原因,在这种特殊情况下,它不被识别。

NameError: undefined local variable or method `session' for #<UserTest:0x0000000658b5c8>

The error happens in the else block in the log_in_as method below:

错误发生在下面的log_in_as方法中的else块中:

test_helper.rb

...

def log_in_as(user, options = {})
  password = options[:password] || 'password'
  remember_me = options[:remember_me] || '1'

  if integration_test?
    post login_path, session: { email: user.email, password: password, remember_me: remember_me }
  else
    session[:user_id] = user.id
  end
end

I call log_in_as in my User test; both of these tests fail.

我在用户测试中调用log_in_as;这两个测试都失败了。

user_test.rb

require 'test_helper'
...
test "login with remembering" do
  log_in_as(@user, remember_me: '1')
  assert_not_nil cookies['remember_token']
end

test "login without remembering" do
  log_in_as(@user, remember_me: '0')
  assert_nil cookies['remember_token']
end
...

And when I remove that line of code from the helper, an error is thrown saying that cookies isn't recognized. What is the issue here?

当我从帮助程序中删除该行代码时,会抛出一个错误,指出cookie无法识别。这是什么问题?

1 个解决方案

#1


6  

The session hash isn't available in models, only in controllers and views and controller and view tests.

会话哈希在模型中不可用,仅在控制器和视图以及控制器和视图测试中可用。

#1


6  

The session hash isn't available in models, only in controllers and views and controller and view tests.

会话哈希在模型中不可用,仅在控制器和视图以及控制器和视图测试中可用。