简体   繁体   English

如何使用设计 user_signed_in? 集成测试中的方法?

[英]How can I use the devise user_signed_in? method in an integration test?

When I have assert user_signed_in?当我assert user_signed_in? in an integration test it says the method is undefined.在集成测试中,它说该方法未定义。 Is there a way I can use this method in my testing?有没有办法在我的测试中使用这种方法? I am using rails 4 and the latest version of devise.我正在使用 rails 4 和最新版本的设计。 Here is my test file:这是我的测试文件:

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

The user_signed_in? user_signed_in? method is included in Devise::Controllers::Helpers module which isn't available in your integration tests so you can't use it.方法包含在Devise::Controllers::Helpers模块中,该模块在您的集成测试中不可用,因此您无法使用它。

You have the option of either mocking this method (which won't really meet your testing needs) or testing that a user is signed in by looking for page content that will only render when the user is signed in like Logout link for example or Signed in successfully message.您可以选择模拟此方法(这不会真正满足您的测试需求)或通过查找仅在用户登录时呈现的页面内容(例如Logout链接或已Signed in successfully )来测试用户是否已登录Signed in successfully消息中。

For your controller tests you can use devise test helpers include Devise::TestHelpers which exposes a sign_in and sign_out methods for you, more on that in the Gem's home page https://github.com/plataformatec/devise对于您的控制器测试,您可以使用设计测试助手include Devise::TestHelpers ,它为您公开sign_insign_out方法,更多关于 Gem 的主页https://github.com/plataformatec/devise

you can't use user_signed_in?你不能使用user_signed_in? inside integration tests as mentioned here before me, but you can write a simple helper method to help you mimic this behavior在我之前提到的集成测试中,但您可以编写一个简单的辅助方法来帮助您模仿这种行为

what i did is ,inside the test_helper.rb :我所做的是在 test_helper.rb 中:

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

it's a pretty hacky solution but it does the trick这是一个非常hacky的解决方案,但它确实有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM