2015-10-05 88 views
0

Rspec失敗,ActionController::UrlGenerationError帶有一個我認爲有效的URL。我已經嘗試了Rspec請求的參數,以及與routes.rb混帳,但我仍然失去了一些東西。Rspec失敗,出現ActionController :: UrlGenerationError

奇怪的是,當使用curl進行本地測試時,它可以100%的工作。

錯誤:

Failure/Error: get :index, {username: @user.username} 
    ActionController::UrlGenerationError: 
     No route matches {:action=>"index", :controller=>"api/v1/users/devices", :username=>"isac_mayer"} 

相關的代碼:

規格/ API/V1 /用戶/ devices_controller_spec.rb

require 'rails_helper' 
RSpec.describe Api::V1::Users::DevicesController, type: :controller do 

    before do 
     @user = FactoryGirl::create :user 
     @device = FactoryGirl::create :device 
     @user.devices << @device 
     @user.save! 
    end 

    describe "GET" do 
     it "should GET a list of devices of a specific user" do 
      get :index, {username: @user.username} # <= Fails here, regardless of params. (Using FriendlyId by the way) 
      # expect.. 
     end 
    end 
end 

應用程序/控制器/ API /v1/users/devices_controller.rb

class Api::V1::Users::DevicesController < Api::ApiController 
    respond_to :json 

    before_action :authenticate, :check_user_approved_developer 

    def index 
    respond_with @user.devices.select(:id, :name) 
    end 

end 

的config/routes.rb中

namespace :api, path: '', constraints: {subdomain: 'api'}, defaults: {format: 'json'} do 
    namespace :v1 do 
     resources :checkins, only: [:create] 
     resources :users do 
     resources :approvals, only: [:create], module: :users 
     resources :devices, only: [:index, :show], module: :users 
     end 
    end 
    end 

相關線路從rake routes

api_v1_user_devices GET /v1/users/:user_id/devices(.:format)  api/v1/users/devices#index {:format=>"json", :subdomain=>"api"} 

回答

1

索引操作需要:user_id參數,但是你有沒有在所提供的一個params哈希。嘗試:

get :index, user_id: @user.id 

該錯誤消息是有點混亂,因爲你實際上並沒有提供一個URL;相反,您正在調用測試控制器上的#get方法,並向其傳遞參數列表,第一個參數是動作(:index),第二個參數是參數哈希。

控制器規格是控制器操作的單元測試,他們期望正確指定請求參數。路由不是控制器的責任;如果你想驗證一個特定的URL被路由到正確的控制器動作(因爲你提到,你使用的是友好的ID),你可能想要考慮一個routing spec

+0

你是明星。其中一件事非常明顯,但我認爲這不是問題!結束使用'get:index,user_id:@ user.username' – Dan

相關問題