1

我无法让 Clearance 身份验证与 Rails 控制器单元测试一起使用。我已按照https://github.com/thoughtbot/clearance “控制器测试助手”中的说明进行操作。您如何对需要身份验证的控制器进行单元测试?

我收到以下错误:

GoalsControllerTest#test_should_get_index:
NoMethodError: undefined method `sign_in_as' for #<GoalsControllerTest:0x007f8c41c6b9c8>
    test/controllers/goals_controller_test.rb:7:in `block in <class:GoalsControllerTest>'

测试/test_helper.rb

require 'clearance/test_unit'

测试/控制器/goals_controller_test.rb

require 'test_helper'

class GoalsControllerTest < ActionDispatch::IntegrationTest
  setup do
    user = User.new(fname: "Test", lname: "User", email: "testuser@test.com", password: "password")
    sign_in_as(user)
    @goal = goals(:one)
  end
4

2 回答 2

2

我和你有同样的问题,但现在这个答案解决了https://github.com/thoughtbot/clearance/issues/695

在测试中启用中间件:

# config/environments/test.rb
MyRailsApp::Application.configure do
  # ...
  config.middleware.use Clearance::BackDoor
  # ...
end

在我的test/test_helper.rb文件中,我编写了以下代码。

class ActionDispatch::IntegrationTest
  def manual_sign_in_as(user)
    post session_url, params: {
      session: {
        email: user.email,
        password: user.password
      }
    }
  end
end

Rails 5 默认从 ActionDispatch::IntegrationTest 子类化控制器测试,所以我只需要按照这里https://github.com/thoughtbot/clearance的自述文件中的说明进行操作。

class PostsControllerTest < ActionDispatch::IntegrationTest
  test "user visits index page while logged in"
    user = User.create!(email: "example@example.com", password: "letmein")
    get links_url(as: user)
    # and
    post links_url(as: user), params: { post: { title: "hi" } }
  end
end
于 2019-05-01T14:17:04.677 回答
0

你在使用 Rails 5 吗?Rails 5 统一集成和控制器测试落后ActionDispatch::IntegrationTest。当您需要时clearance/test_unit,Clearance 只会将其助手添加到ActionController::TestCase.

我认为你可以这样做:

class ActionDispatch::IntegrationTest
  include Clearance::Testing::ControllerHelpers
end

在您的test_helper.rb文件中,以便访问这些测试中的助手。但是,我不确定助手本身是否会在这种情况下工作。

如果您可以尝试一下,那将很有帮助。这也应该在 Clearance 中修复。由于我自己不使用 TestUnit/MiniTest,我有时会错过这样的事情。

于 2017-03-07T21:43:54.743 回答