0

我是通过Michael Hartl的Rails教程工作的Rails初学者,并且收到错误,我不知道如何解决。作为参考,这是为了实施列表9.24(https://www.railstutorial.org/book/advanced_login)中的更改。在集成测试中访问会话

我跳过了第9章(因为它被认为是可选的),但在第10章中它要求包含在列表9.24中所做的更改,所以我做了,而且我的测试仍然失败。

这是当我跑我收到错误轨测试

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>' 

测试(测试/集成/ users_edit_test.rb),这些失败是:

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 

,这里是正在调用集成/ test_helper方法

# Log in as a particular user. 
    def log_in_as(user) 
    session[:user_id] = user.id 
    end 

什么是特别令人困惑的是th在测试帮助程序中还有另一种使用会话的方法,并且在user_login_test中调用时可以正常工作。

任何帮助将不胜感激!

回答

0

对于任何人碰到这个问题即将在未来的利益,集成测试,您需要定义一个test_helper方法的帖子到会话控制器创建方法,而不是专门修改会话,例如

class ActionDispatch::IntegrationTest 
    def log_in_as(user, password: 'password') 
     post login_path, params: { session: { email: user.email, password: password} } 
    end 
end 

的原因,你的其他会话方法的工作原理是,因为它没有任何分配到会话哈希值,如果值存在与否只是检查。对于集成测试,您不能直接用永久性修改会话哈希。

相关问题