RSpec无法找到嵌套资源的路由

时间:2017-02-08 16:34:42

标签: ruby-on-rails ruby rspec ruby-on-rails-5

我尝试在嵌套的resources控制器上运行单元测试时处理一个看似奇怪的问题。这是我的设置:

routes.rb

Rails.application.routes.draw do
  scope module: 'api' do
    namespace :v1 do
      resources :users do
        resources 'item-configurations',
          controller: :item_configuration,
            as: :item_configurations,
            on: :member
      end
    end
  end
end

app/controllers/api/v1/item_configurations_controller.rb

module Api::V1                              
  class ItemConfigurationsController < ApplicationController
    def show
      @user = authorize User.find(params[:user_id])      
      @item_configuration = authorize @user.item_configurations.find(params[:id])

      success @item_configuration
    end
  end
end

最后,spec/controllers/api/v1/item_configurations_controller_spec.rb

require 'rails_helper'

describe Api::V1::ItemConfigurationsController do
  describe '#show' do
    it 'renders an item configuration' do
      user = FactoryGirl.create(:user)
      configuration = FactoryGirl.create(:item_configuration)

      get :show, params: {user_id: user.id, id: configuration.id}
      expect(response.status).to equal(200)
    end
  end
end

当我向/users/1/item-configurations/4提出请求时,我能够得到回复,正如我所期待的那样。问题来自于我运行rspec时出现以下错误:

  1) Api::V1::ItemConfigurationsController#show renders an item configuration
     Failure/Error: get :show, params: {user_id: user.id, id: configuration.id}

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"api/v1/item_configurations", :id=>1, :user_id=>1}

通常,当请求中缺少参数时会出现这些错误,但在这种情况下,所有内容都显示在那里(user_idid)。我也在控制器上的其他路由上尝试了这个(#index在发送GET但在rspec中不起作用时也有效),添加format: :json参数等等但是似乎没有什么能解决它。

我疯了还是有一些简单的我在这里失踪了?

1 个答案:

答案 0 :(得分:2)

嗯,除了路线中的拼写on(单数,而控制器是复数),您在resources上指定resources参数。它似乎是app.url_for({:action=>"show", :controller=>"api/v1/item_configurations", :id=>"2", :user_id=>"1"}) => ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"api/v1/item_configurations", :id=>"2", :user_id=>"1"} app.url_for({:action=>"show", :controller=>"api/v1/item_configurations", :id=>"2", :user_id=>"1", on: :member}) => "http://www.example.com/v1/users/1/item_configurations/2" 的约束,而不是&#34;类型&#34;互动。

来自控制台:

member

因此,在路由中使用... resources :users do member do resources :configuration_items end end ... 块来实现所需的行为:

{{1}}