首页 > 解决方案 > 测试 ActionController::RoutingError: 未初始化的常量 V1::LocationsController

问题描述

在 Ruby on rails 5 上运行测试时出现未初始化的常量错误...

我正在使用命名空间 - v1 为我的 api 控制器编写测试用例,但似乎 ROR 不理解命名空间 V1 的存在。

当我运行“rails routes”时,这就是我得到的:

             v1_locations GET    /v1/locations(.:format)                                                                  v1/locations#index
                          POST   /v1/locations(.:format)                                                                  v1/locations#create
              v1_location GET    /v1/locations/:id(.:format)                                                              v1/locations#show
                          PATCH  /v1/locations/:id(.:format)                                                              v1/locations#update
                          PUT    /v1/locations/:id(.:format)                                                              v1/locations#update
                          DELETE /v1/locations/:id(.:format)                                                              v1/locations#destroy

这就是我的测试文件中的内容......

class V1::LocationControllerTest < ActionDispatch::IntegrationTest

  def setup()
    # A bunch of stuff here
  end

  test "cannot retrieve a list of locations without a valid token" do
    get v1_locations_url
    assert_response :unauthorized
  end

  # More tests here...

end

这就是我的控制器的样子

class V1::LocationController < ApplicationController

    # To be filled once tests run and fail

end

这是我收到的错误消息...

Error:
V1::LocationControllerTest#test_cannot_create_a_location_without_a_valid_token:
ActionController::RoutingError: uninitialized constant V1::LocationsController
    test/controllers/v1/location_controller_test.rb:32:in `block in <class:LocationControllerTest>'


bin/rails test test/controllers/v1/location_controller_test.rb:31

当我向 /v1/locations 发送 GET 请求时出现页面未找到错误也很有趣

嗯......我在这里错过了什么?

谢谢,

标签: ruby-on-railserror-handling

解决方案


检查它说的错误日志ActionController::RoutingError: uninitialized constant V1::LocationsController,而您的控制器名称是LocationController.

请将其重命名为LocationsController并将文件重命名为locations_controller.rb.

您可以在此处获得有关此的更多见解


推荐阅读