0

我正在处理我实现的搜索端点的测试和文档。我无法正确添加查询参数。基本上请求 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
4

1 回答 1

0

你的控制器有两个参数,过滤器和项目。类型不是参数。

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

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

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

于 2021-02-17T08:02:18.473 回答