2017-02-08 4 views
1

ネストされたresourcesコントローラでユニットテストを実行しようとしているときに、一見奇妙な問題を扱っています。ここに私の設定です:RSpecがネストされたリソースのルートを見つけることができません

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 

私は​​に要求を行うとき、私はすることができますよ私が期待しているのと同じように、応答を得る。問題は、私は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)があるように見えます。私もコントローラの他のルートでこれを試しました(#indexGETを送信しても動作しますが、rspecでは動作しません)、format: :json paramなどを追加しても何も解決しないようです。

私は狂っているのですか、ここには何か簡単なことがありますか?

+0

私には、[この]に似ています(https://github.com/ rspec/rspec-rails/issues/1586)の問題です。それが役立つかどうかわからない。私は 'Rails.application.routes.draw'を' Yourappname :: Application.routes.draw'に改名しようとします。 – mutantkeyboard

+0

何かが見つからないか、エラー出力に 'TrayConfigurationsController'を推測していますが、' ItemConfigurationsController ' 。 'log/test.log'に奇妙なものは何ですか? – Anthony

+0

、それは間違いです。私は、より一般的にするために、この質問の目的のためにいくつかのモデルの名前を変更しました。私は最新の編集でそれを修正しました。 –

答えて

2

あなたのルートには、controller: :item_configuration(単数形、コントローラは複数形)以外に、resourcesonというパラメータを指定します。これは、相互作用の「タイプ」としてではなく、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" 

そのため、目的の動作を達成するためのルートでmemberブロックを使用します。

... 
resources :users do 
    member do 
    resources :configuration_items 
    end 
end 
... 
+0

はい、それでした!本当にありがとう、あなたが知っているより多くの時間/正気を救ってくれました。 –

関連する問題