我正在构建一个API,在编写测试时,我遇到了一个奇怪的UrlGenerator错误。
我在版本1上有一个API,这是我的用户控制器。
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发布于 2018-10-04 19:13:58
问题是,您定义的显示路由需要一个:id参数,但是测试中对get :show的调用不会发送它。
在Rspec中,您可以发送id,其内容如下:
get :show, params: { id: @user.id }, format: :json
https://stackoverflow.com/questions/52649846
复制相似问题