Rspec 当路由确实存在时路由规范失败

Rspec routing specs fail when route DOES exist

我正在尝试测试命名空间 Rails 控制器操作的路由,但有些地方设置不正确。

我已经查看了以下问题,其中 none 甚至似乎回答了手头的问题,更不用说给我的问题的答案了:

与其说是我向操作传递了错误的参数,不如说是在此测试的上下文中路由根本不匹配。我在这里错过了什么?

config/routes.rb(使用版本主义者gem):

...
api_version(module: 'api/v1', path: {value: 'v1'}) do
  namespace :nphase do
    resource :device_service, controller: 'device_service', only: :none, format: :json do
      collection do
        post :get_device_information
      end
    end
  end
end
...

app/controllers/api/v1/device_service_controller.rb:

module Api                                               
  module V1                                              

    class DeviceServiceController < ApplicationController
      respond_to :json                                   

      def get_device_information                       
        respond_with json: {"success" => true}           
      end                                                
    end                                                  

  end                                                    
end                                                      

rake routes |grep nphase的输出:

get_device_information_v1_nphase_device_service POST    /v1/nphase/device_service/get_device_information(.:format) api/v1/nphase/device_service#get_device_information {:format=>:json}

spec/routing/api/v1/device_service_routing_spec.rb:

require 'spec_helper'

describe 'routes for DeviceService' do
  it 'routes correctly' do
    expect(post('/v1/nphase/device_service/get_device_information')).to route_to(
      controller: 'api/v1/device_service',
      action: 'get_device_information'
    )
  end
end

测试失败:

Failure/Error: expect(post('/v1/nphase/device_service/get_device_information')).to route_to(
  No route matches "/v1/nphase/device_service/get_device_information"

根据 运行 你的规范(尽管在 Rails 4 中),我得到了这个错误:

Failure/Error: expect(post: '/v1/nphase/device_service/get_device_information').to route_to(
       A route matches "/v1/nphase/device_service/get_device_information", but references missing controller: Api::V1::Nphase::DeviceServiceController
     # ./spec/controller_spec.rb:5:in `block (2 levels) in <top (required)>'

这告诉我们您的控制器不在 Nphase 模块中。

通过使用 namespace,您告诉 Rails 在特定模块中搜索控制器。

所以要么将控制器放在正确的模块中(并相应地更改目录结构),要么告诉 rails 在正确的位置查找控制器(来自 the Rails guides):

If you want to route /admin/articles to ArticlesController (without the Admin:: module prefix), you could use:

 scope '/admin' do
   resources :articles, :comments
 end