【问题标题】:How can I use the devise user_signed_in? method in an integration test?如何使用设计 user_signed_in?集成测试中的方法?
【发布时间】:2015-09-13 21:34:18
【问题描述】:

当我在集成测试中有assert user_signed_in? 时,它说该方法未定义。有没有办法可以在我的测试中使用这种方法?我正在使用 rails 4 和最新版本的设计。这是我的测试文件:

require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest

test "valid signup information" do
    get new_user_registration_path
    assert_difference 'User.count', 1 do
      post_via_redirect user_registration_path, 
                                     user: { first_name: "Example",
                                             last_name:  "User",
                                             email:      "user@example.org",
                                             password:              "password",
                                             password_confirmation: "password" }
    end
    assert_template 'activities/index'
    assert user_signed_in?
  end

【问题讨论】:

  • 我们需要的不止这些。请阅读有关如何创建最小、完整且可验证的示例的建议:stackoverflow.com/help/mcve
  • 抱歉,已修复

标签: ruby-on-rails devise


【解决方案1】:

user_signed_in? 方法包含在 Devise::Controllers::Helpers 模块中,该模块在您的集成测试中不可用,因此您无法使用它。

您可以选择模拟此方法(这不会真正满足您的测试需求)或通过查找仅在用户登录时才会呈现的页面内容来测试用户是否已登录,例如 Logout例如链接或Signed in successfully 消息。

对于您的控制器测试,您可以使用设计测试助手 include Devise::TestHelpers,它为您公开了 sign_insign_out 方法,更多信息请参见 Gem 主页 https://github.com/plataformatec/devise

【讨论】:

    【解决方案2】:

    你不能在我之前提到的集成测试中使用user_signed_in?,但你可以编写一个简单的辅助方法来帮助你模仿这种行为

    我所做的是,在 test_helper.rb 中:

     def is_logged_in?
      request.env['warden'].authenticated?(:user)
     end
    

    这是一个非常老套的解决方案,但它可以解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多