集成测试中的访问会话 [英] Accessing session in integration test
问题描述
我是通过Michael Hartl的Rails教程工作的Rails初学者,并且收到一个错误,我不知道如何解决.作为参考,这是为了实现清单9.24( https://www.railstutorial.org/book /advanced_login ).
I'm a Rails beginner working through Michael Hartl's Rails Tutorial and am receiving an error I have no idea how to fix. For reference, this is for implementing the changes in listing 9.24 (https://www.railstutorial.org/book/advanced_login).
我跳过了第9章(因为它可能是可选的),但在第10章中要求包括清单9.24中所做的更改,所以我这样做了,但我的测试仍然失败.
I skipped chapter 9 (since it is supposedly optional) but in Chapter 10 it asks to include the changes made in listing 9.24 so I did and my tests are still failing.
这是我在运行rails test时收到的错误
This is the error I am receiving when I run rails test
Error:
UsersEditTest#test_unsuccessful_edit:
NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:18:in `log_in_as'
test/integration/users_edit_test.rb:14:in `block in <class:UsersEditTest>'
bin/rails test test/integration/users_edit_test.rb:12
E
Error:
UsersEditTest#test_successful_edit:
NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:18:in `log_in_as'
test/integration/users_edit_test.rb:28:in `block in <class:UsersEditTest>'
失败的测试(在test/integration/users_edit_test.rb中)是:
The tests (in test/integration/users_edit_test.rb) that are failing are:
test "successful edit" do
log_in_as(@user)
get edit_user_path(@user)
... end
test "unsuccessful edit" do
log_in_as(@user)
get edit_user_path(@user)
... end
这是被调用的integration/test_helper方法
and here is the integration/test_helper method that is being called
# Log in as a particular user.
def log_in_as(user)
session[:user_id] = user.id
end
尤其令人困惑的是,测试帮助器中还有另一种方法也使用会话,并且在user_login_test中被调用可以很好地工作.
What is especially confusing is that there is another method in the test helper that also uses sessions, and is called in user_login_test which works fine.
任何帮助将不胜感激!
推荐答案
为了将来遇到这个问题的任何人的利益,对于集成测试,您需要定义一个test_helper方法,该方法发布到会话控制器create方法中,而不是专门修改会话,例如
For the benefit of anyone coming across this question in the future, for integration tests you'll need to define a test_helper method that posts to the session controllers create method, not modify the session specifically e.g.
class ActionDispatch::IntegrationTest
def log_in_as(user, password: 'password')
post login_path, params: { session: { email: user.email, password: password} }
end
end
您的其他会话方法起作用的原因是,它没有为会话哈希分配任何内容,仅检查值是否存在.对于集成测试,您不能直接永久地修改会话哈希.
The reason your other session method works is because it's not assigning anything to the session hash, just checking if a value exists or not. For integration tests, you can't modify the session hash directly with permanence.
这篇关于集成测试中的访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!