gpt4 book ai didi

ruby-on-rails - 如何在 Rails4 测试中使用 Devise 登录/注销用户

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:49 27 4
gpt4 key购买 nike

我正在努力确保使用 Devise in Rails 4 维护正确的用户访问权限,但我很难让用户登录到测试套件中。

最简单的情况:

require 'test_helper'
include Devise::TestHelpers

class SiteLayoutTest < ActionDispatch::IntegrationTest

def setup
@user = users(:test1)
end

test "logged in should get index" do
sign_in @user
get users_path
assert_response :success
assert_select "title", "User Index"
end
end

到目前为止,除了实现 Devise 和具有适当操作的用户 Controller 之外,我没有做更多的事情。

我一直得到:NoMethodError: undefined method 'env' for nil:NilClass,具体指的是包含 sign_in @user 的行,我可以找到 people 的其他实例遇到同样的错误,但似乎从未找到解决我试图解决的问题的实际解决方案。

我如何使用 Devise in Rails 4 登录用户以进行测试?谢谢。

编辑:

fixtures/users.yml

test1:
id: '1'
email: 'test1@example.com'
encrypted_password: <%= Devise::Encryptor.digest(User, "password") %>
created_at: <%= Time.now - 6.minutes %>
updated_at: <%= Time.now - 4.minutes %>

原位解决方案:

test "logged in should get index" do
post user_session_path, 'user[email]' => @user.email, 'user[password]' => 'password'
get users_path
assert_response :success
assert_select "title", "User Index"
end

最佳答案

这是来自他们的 docs :

"Do not use Devise::TestHelpers in integration tests."

您必须手动登录。这是一个测试网站的示例,该网站不允许用户在未登录的情况下访问根路径。您可以在支持文件中创建一个方法来手动登录用户,然后在您想要登录时调用它用户,这样您就不必在每次需要登录用户时都使用此代码。

require 'test_helper'

class UserFlowsTest < ActionDispatch::IntegrationTest
test "signed in user is redirected to root_path" do
get user_session_path
assert_equal 200, status
@david = User.create(email: "david@mail.com", password: Devise::Encryptor.digest(User, "helloworld"))
post user_session_path, 'user[email]' => @david.email, 'user[password]' => @david.password
follow_redirect!
assert_equal 200, status
assert_equal "/", path
end

test "user is redirected to sign in page when visiting home page" do
get "/"
assert_equal 302, status
follow_redirect!
assert_equal "/users/sign_in", path
assert_equal 200, status
end
end

编辑:以防万一它在未来有帮助。您可以使用 Warden Test Helpers用于集成测试,但上面的方法是更好的测试。这是一个工作示例:

require 'test_helper'
include Warden::Test::Helpers
class UserFlowsTest < ActionDispatch::IntegrationTest
test "user can see home page after login" do
@david = User.create(email: "david@mail.com", password: Devise::Encryptor.digest(User, "helloworld"))
login_as(@david)
get "/"
assert_equal 200, status # User gets root_path because he loged in
assert_equal "/", path
logout
get "/"
assert_equal 302, status # User is redirected because he loged out
Warden.test_reset! #reset Warden after each example
end
end

关于ruby-on-rails - 如何在 Rails4 测试中使用 Devise 登录/注销用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com