【问题标题】:How can I get Minitest to resolve helper in a controller test?如何让 Minitest 在控制器测试中解析助手?
【发布时间】:2020-07-24 23:14:59
【问题描述】:

我有一个失败的控制器测试,它只是测试索引路由是否返回 200 响应。

有问题的控制器有before_action :is_authenticated?,其中is_authenticated? 定义在ActionController 中包含的帮助器auth_helper.rb 中(因为我的意图是跨多个控制器使用它)。

当我与我的应用程序交互时,is_authenticated? 方法会正常执行。当我运行我的测试套件时,我收到以下错误消息:

# Running:

....E

Error:
EventsControllerTest#test_should_fail_creation_with_invalid_data:
NoMethodError: undefined method `is_authenticated?' for #<Api::V1::EventsController:0x00007f943966c2c0>
    test/controllers/events_controller_test.rb:19:in `block in <class:EventsControllerTest>'

rails test test/controllers/events_controller_test.rb:18

这是我的测试:

require 'test_helper'

class EventsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @event = Event.first
    
    register
  end
  
  test "should get index" do
    get "/api/v1/events"
    assert_response :success

    events = JSON.parse(response.body)
    assert_equal(events.length, 2)
  end
end

这是auth_helper.rb中的代码:

module AuthHelper
    def is_authenticated?
        if is_user_signed_in?
            return true
        else
            render json: { error: "You must be logged in" }, status: :unauthorized 
        end
    end
end

我怎样才能让我的测试使用帮助程序正确模拟请求,就像实时请求一样?

我尝试在测试中要求帮助程序并在设置代码中定义它,但这似乎没有帮助。

我是 Rails 新手,因此我们将不胜感激任何反馈。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby minitest


    【解决方案1】:

    我最终解决了我遇到的问题,方法是将代码放在关注点而不是帮助模块中。

    通过将代码包含在关注点中,然后将关注点添加到 ApplicationControlleris_authenticated? 函数会被我的代码拾取,并在测试套件执行期间得到解决。

    我仍然不清楚常规模块和 rails 关注点如何解决之间的区别,但在这种情况下添加关注点已经实现了预期的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2011-06-07
      • 2019-04-30
      • 2011-12-08
      • 2015-11-17
      • 2018-06-28
      相关资源
      最近更新 更多