2015-10-05 86 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

相关问题