加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:48:31 所属栏目:百科 来源:网络整理
导读:我正在努力确保使用Devise in Rails 4来维护正确的用户访问,并且我很难在测试套件中记录用户. 最简单的情况: require 'test_helper' include Devise::TestHelpersclass SiteLayoutTest ActionDispatch::IntegrationTest def setup @user = users(:test1) en
我正在努力确保使用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和Users控制器.

我一直得到:NoMethodError:nil的未定义方法’env’:NilClass,特指含有sign_in @user的行,我可以找到其他人得到相同错误的实例,但似乎从来没有找到问题的实际解决方案我我试图解决.

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

编辑:

灯具/ 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","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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读