【问题标题】:Rspec fails with ActionController::UrlGenerationErrorRspec 失败并出现 ActionController::UrlGenerationError
【发布时间】:2015-10-05 16:07:42
【问题描述】:

Rspec 失败,ActionController::UrlGenerationError 带有我认为有效的 URL。我试过弄乱 Rspec 请求的参数,以及摆弄 routes.rb,但我仍然缺少一些东西。

奇怪的是,在本地使用 curl 进行测试时,它可以 100% 正常工作。

错误:

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

相关代码:

spec/api/v1/users/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

app/controllers/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"}

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    索引操作需要:user_id 参数,但您没有在参数哈希中提供一个。试试:

    get :index, user_id: @user.id
    

    错误消息有点令人困惑,因为您实际上并没有提供 URL;相反,您在测试控制器上调用 #get 方法,并将参数列表传递给它,第一个是操作 (:index),第二个是参数哈希。

    控制器规范是控制器操作的单元测试,它们期望正确指定请求参数。路由不是控制器的责任;如果您想验证特定 URL 是否被路由到正确的控制器操作(因为您提到,您使用的是友好 ID),您可能需要考虑使用 routing spec

    【讨论】:

    • 你是明星。其中一件很明显的事情,但我认为不是问题!最终使用get :index, user_id: @user.username
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多