【问题标题】:Rails Clearance, Unit Test ControllerRails 间隙,单元测试控制器
【发布时间】:2017-03-05 03:44:43
【问题描述】:

我无法让 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/test_helper.rb

require 'clearance/test_unit'

test/controller/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

【问题讨论】:

  • 'sign_in_as' 方法是在 ApplicationController 中定义的还是在辅助模块中定义的?

标签: ruby-on-rails unit-testing clearance


【解决方案1】:

我和你有同样的问题,但现在这个答案解决了 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

默认情况下,来自 ActionDispatch::IntegrationTest 的 Rails 5 子类控制器测试,所以我只需要按照这里 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

【讨论】:

    【解决方案2】:

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

    我认为你可以这样做:

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

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

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

    【讨论】:

    • user = User.new(fname: "Test", lname: "User", email: "testuser@test.com", password: "password") sign_in_as(user)
      错误:NoMethodError:未定义方法 env' for nil:NilClass test/controllers/goals_controller_test.rb:9:in block in ' 我是 Rails 新手。如果有任何关于单元测试许可的工作示例会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 2017-06-26
    • 2020-08-12
    • 1970-01-01
    • 2016-07-29
    • 2018-03-09
    相关资源
    最近更新 更多