我目前正在Rails中开发一个API端点。如果我需要的数据无效,我想确保端点响应具有正确的错误状态。我需要一个id数组。其中一个无效值是空数组。
有效
{ vendor_district_ids: [2, 4, 5, 6]}
无效
{ vendor_district_ids: []}
使用RSpec请求Spec
所以我想有一个请求规范来控制我的行为。
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
块中的param中使用了一个空数组。
控制器内部值
在我的控制器中,我用
params.require(:vendor_district_ids)
其值如下
<ActionController::Parameters {"vendor_district_ids"=>[""], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
vendor_district_ids
的值是一个空字符串数组。当我用postman
写一篇文章时,我没有相同的值。
与postman的值
如果我发布
{ "vendor_district_ids": [] }
控制器将接收
<ActionController::Parameters {"vendor_district_ids"=>[], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
这里是空数组。
提问
是我在请求规范中做错了什么,还是这是来自RSpec
的bug?
4条答案
按热度按时间1rhkuytd1#
找到答案了!
问题
问题是在Rack的
query_parser
内部发现的,而不是像前面的答案所示的那样实际上在Rack-test内部。"paramName[]="
到{"paramName":[""]}
的实际转换发生在Rack的query_parser中。问题的一个例子:
解决方案
通过使用
'require 'json'
将JSON gem添加到您的应用程序中,并使用.to_json
附加您的param散列,将参数转换为JSON。并在RSPEC请求中指定此请求的内容类型为JSON。
通过修改上面的示例来举例:
bvjveswy2#
对于每个人都想知道-有一个快捷的解决方案:
gzjq41n43#
这实际上是由
rack-test >= 0.7.0
引起的[1]。它将空数组转换为
param[]=
,稍后解码为['']
。如果你尝试运行相同的代码,例如
rack-test 0.6.3
你会看到vendor_district_ids
根本没有被添加到查询中:[1][https://github.com/rack-test/rack-test/commit/ece681de8ffee9d0caff30e9b93f882cc58f14cb](https://github.com/rack-test/rack-test/commit/ece681de8ffee9d0caff30e9b93f882cc58f14cb)
bmvo0sr54#
我不能发送它作为json在我的情况下,因为我发送也发送文件作为multipart形式。我的解决方法是在数组中放入一个空字符串。