ruby-on-rails - RSpec 请求规范发布一个空数组
问题描述
我目前正在 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
块内的参数中使用了一个空数组。
控制器内部的值
在我的控制器中,我正在获取数据
params.require(:vendor_district_ids)
值如下
<ActionController::Parameters {"vendor_district_ids"=>[""], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
的值vendor_district_ids
是一个空字符串数组。当我用postman
.
邮递员的价值
如果我发帖
{ "vendor_district_ids": [] }
控制器将收到
<ActionController::Parameters {"vendor_district_ids"=>[], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>
这里的数组是空的。
问题
我在请求规范中做错了什么还是这是一个错误RSpec
?
解决方案
找到了答案!
问题
query_parser
正如前面的答案所示,问题出现在 Rack内部,而不是实际上在 rack-test 内部。
"paramName[]="
into的实际翻译{"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,方法是使用 JSON gem 并将'require 'json'
您的参数哈希附加到您的应用程序中.to_json
。
并在您的 RSPEC 请求中指定此请求的内容类型为 JSON。
通过修改上面的例子的一个例子:
post '/posts', { ids: [] }.to_json, { "CONTENT_TYPE" => "application/json" }
{"ids"=>[]} # explicitly sending JSON will work nicely
推荐阅读
- postgresql - 将 0 放在字符串中以使其在 SQL 中具有一定长度
- node.js - 如何使用 NodeJS 模拟对 dynamodb 的插入?
- c - 为什么一个 for 循环按预期工作,而另一个没有迭代?
- c# - 成功构建后无法启动代码的 Visual Studio 新设置
- kafka-consumer-api - KafkaConsumer 如何识别它需要检查的模式
- twitter-bootstrap - 如何在 Bootstrap 5 中使用 CSS 变量?
- r - 如何编写一个函数来给出 R 中输入向量数字的发音?
- python - Pytorch TypeError:只有单个元素的整数张量可以转换为索引
- android - 应用启动时 Android ContentResolver.getType 未准备好
- html - CSS - 防止具有未知高度的相对 div 与下面的 div 重叠