我目前正在 Rails 中开发 API 端点。如果我需要的数据无效,我想确保端点响应具有正确的错误状态。我需要一个 id 数组。其中一个无效值是空数组。
有效
{ vendor_district_ids: [2, 4, 5, 6]}
无效
{ vendor_district_ids: []}
使用 RSpec 请求规范
所以我想要一个请求规范来控制我的行为。
require 'rails_helper'
RSpec.describe Api::PossibleAppointmentCountsController, type: :request do
let(:api_auth_headers) do
{ 'Authorization' => 'Bearer this_is_a_test' }
end
describe 'POST /api/possible_appointments/counts' do
subject(:post_request) do
post api_my_controller_path,
params: { vendor_district_ids: [] },
headers: api_auth_headers
end
before { post_request }
it { expect(response.status).to eq 400 }
end
end
如您所见,我在 subject
block 内的参数中使用了一个空数组。
Controller 内的值
在我的 Controller 中,我正在获取数据
params.require(:vendor_district_ids)
值如下
<ActionController::Parameters {"vendor_district_ids"=>[""], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
vendor_district_ids
的值是一个包含空字符串的数组。当我用 postman
发帖时,我没有相同的值。
postman 的值(value)
如果我发帖
{ "vendor_district_ids": [] }
Controller 将接收
<ActionController::Parameters {"vendor_district_ids"=>[], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
这里是空数组。
问题
我是在请求规范中做错了什么,还是 RSpec
的错误?
最佳答案
找到答案了!
问题
问题是在 Rack 的 query_parser
中发现的,而不是像前面的答案所指出的那样实际上是在 rack-test 中。
"paramName[]="
到 {"paramName":[""]}
的实际翻译发生在 Rack 的 query_parser 中。 .
问题示例:
post '/posts', { ids: [] }
{"ids"=>[""]} # By default, Rack::Test will use HTTP form encoding, as per docs: https://github.com/rack/rack-test/blob/master/README.md#examples
解决方案
将您的参数转换为 JSON,方法是使用 'require 'json'
将 JSON gem 引入您的应用程序并使用 .to_json
附加您的参数散列。
并在您的 RSPEC 请求中指定该请求的内容类型为 JSON。
修改上面例子的例子:
post '/posts', { ids: [] }.to_json, { "CONTENT_TYPE" => "application/json" }
{"ids"=>[]} # explicitly sending JSON will work nicely
关于ruby-on-rails - RSpec 请求规范发布一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51396194/