Rails Api测试UrlGenerationError

时间:2018-10-04 14:58:37

标签: ruby-on-rails ruby

我正在构建API,并且在编写测试时遇到了一个奇怪的UrlGenerator错误。

我在版本1上有一个API,这是我的Users控制器。

class Api::V1::UsersController < ApplicationController
  respond_to :json

  def show
    respond_with User.find(params[:id])
  end
end

这是该用户控制器的规范

require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
  before(:each) { request.headers['Accept'] = "application/vnd.marketplace.v1" }

  describe "GET #show" do
    before(:each) do
      @user = FactoryBot.create :user
      get :show, format: :json
    end

    it "returns the information about a reporter on a hash" do
      user_response = JSON.parse(response.body, symbolize_names: true)
      expect(user_response[:email]).to eql @user.email
    end

    it { should respond_with 200 }
  end
end

运行此规范时,我收到以下错误消息:`Failure / Error:get:show,format::json

 ActionController::UrlGenerationError:
   No route matches {:action=>"show", :controller=>"api/v1/users", :format=>:json}`

我的API只有一条路由:

api_user GET  /users/:id(.:format) api/v1/users#show {:subdomain=>"api", :format=>:json}

有人知道我为什么会收到此错误吗?在我看来,根据api路由列表返回的路由,这应该可以正常工作。我的routes.rb文件在下面列出:

namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/'  do
    scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
      resources :users, :only => [:show]
    end
  end

1 个答案:

答案 0 :(得分:0)

问题是您定义的显示路线需要一个:id参数,但是测试中对get :show的调用却没有发送它。

从Rspec中,您可以使用以下方式发送ID:

get :show, params: { id: @user.id }, format: :json