首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails Api测试UrlGenerationError

Rails Api测试UrlGenerationError
EN

Stack Overflow用户
提问于 2018-10-04 14:58:36
回答 1查看 39关注 0票数 0

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

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

代码语言:javascript
复制
class Api::V1::UsersController < ApplicationController
  respond_to :json

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

以下是该用户控制器的规范

代码语言:javascript
复制
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

代码语言:javascript
复制
 ActionController::UrlGenerationError:
   No route matches {:action=>"show", :controller=>"api/v1/users", :format=>:json}`

我的API只有一条路径:

代码语言:javascript
复制
api_user GET  /users/:id(.:format) api/v1/users#show {:subdomain=>"api", :format=>:json}

有人知道我为什么会犯这个错误吗?在我看来,基于从api路由列表返回的路由,这应该是可行的。下面列出了我的routes.rb文件:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-04 19:13:58

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

在Rspec中,您可以发送id,其内容如下:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52649846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档