【问题标题】:Composed query params for rspec api documentationrspec api 文档的组合查询参数
【发布时间】:2021-02-17 06:49:35
【问题描述】:

我正在处理我实现的搜索端点的测试和文档。我无法正确添加查询参数。基本上请求 url 应该是这样的

"/api/v3/workspaces/1/searches?filter[query]=b&filter[type]=ct:Tag,User,WorkingArea"

我的控制器是这样的

class SearchesController < ApiV3Controller
    load_and_authorize_resource :workspace
    load_and_authorize_resource :user, through: :workspace
    load_and_authorize_resource :working_area, through: :workspace
    load_and_authorize_resource :tag, through: :workspace

    def index
      @resources = relevant_search_results

      render_json(@resources)
    end

    private

    def ability_klasses
      [WorkspaceAbility, UserWorkspaceAbility, WorkingAreaAbility, TagAbility]
    end

    def relevant_search_results
      query = filtered_params[:query]
      types = filtered_params[:type]
      items = params[:items]
      GlobalSearcher.new(query, types, items, @workspace).relevant_search_results
    end

    def render_json(resources)
      render json: resources, status: :ok
    end

    def filtered_params
      params.require(:filter).permit(:query, :type)
    end
  end

该功能可以正常工作。问题在于测试。规格文件如下所示:

resource "Searches", :include_basic_variables, type: :api do

parameter :filter
parameter :type
parameter :items
let(:query) { "be" }
let(:type) { "ct:Tag,User,WorkingArea" }
let(:items) { "3" }
let_it_be(:workspace_id) { company.id }
explanation "Searches resource"
 route "/api/v3/workspaces/:workspace_id/searches", "Index" do
with_options with_example: true, required: true do
  parameter :workspace_id, "Workspace ID", type: :integer, example: 1
end


get "List all the relevant items" do
  context "Authenticated" do
    before { sign_in(admin) }

    example 'Search results' do
      do_request

      expect(query_string).to eq("filter[query]=b&filter[type]=ct:Tag,User,WorkingArea&items=3")
      expect(status).to eq 200
    end
  end
end

我在运行 rspec 时遇到的错误是

expected: "filter[query]=b&filter[type]=ct:Tag,User,WorkingArea&items=3"
got: "query=be&type=ct%3ATag%2CUser%2CWorkingArea&items=3

【问题讨论】:

  • 是否需要测试查询字符串?查询字符串可能会更改的实现细节。相反,测试它是否具有预期的效果。
  • 什么是:include_basic_variables:
  • @Schwern 我同意,我使用它来了解请求的外观并在此处提供清晰的错误日志。
  • @Schwern 我们实现了 :include_basic_variables 以包含工厂创建的所有对象,这些对象可在规范文件中反复使用。

标签: ruby-on-rails rspec rspec-api-documentation


【解决方案1】:

你的控制器有两个参数,filter 和 items。 type 不是参数。

你永远不会给过滤器一个值。 filter 是带有键查询和类型的哈希参数,但您尚未建立该连接。我的理解是 rspec-api-documentation 会从值中推断出类型。

parameter :filter
parameter :items
let(:filter) do
  { query: "be", type: "ct:Tag,User,WorkingArea" }
end
let(:items) { "3" }

请注意,您不应该直接测试查询字符串,这是一个实现细节。您应该正在测试该查询是否具有预期的效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    相关资源
    最近更新 更多