【发布时间】: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