【发布时间】: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