ruby RSpec request spec post an empty array

bn31dyow  于 12个月前  发布在  Ruby
关注(0)|答案(4)|浏览(107)

我目前正在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?

1rhkuytd

1rhkuytd1#

找到答案了!

问题

问题是在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

解决方案

通过使用'require 'json'将JSON gem添加到您的应用程序中,并使用.to_json附加您的param散列,将参数转换为JSON。
并在RSPEC请求中指定此请求的内容类型为JSON。
通过修改上面的示例来举例:

post '/posts', { ids: [] }.to_json, { "CONTENT_TYPE" => "application/json" }
{"ids"=>[]} # explicitly sending JSON will work nicely
bvjveswy

bvjveswy2#

对于每个人都想知道-有一个快捷的解决方案:

post '/posts', params: { ids: [] }, as: :json
gzjq41n4

gzjq41n43#

这实际上是由rack-test >= 0.7.0引起的[1]。
它将空数组转换为param[]=,稍后解码为['']
如果你尝试运行相同的代码,例如rack-test 0.6.3你会看到vendor_district_ids根本没有被添加到查询中:

# rack-test 0.6.3
Rack::Test::Utils.build_nested_query('a' => [])
# => ""

# rack-test >= 0.7.0
Rack::Test::Utils.build_nested_query('a' => [])
# => "a[]="

Rack::Utils.parse_nested_query('a[]=')
# => {"a"=>[""]}

[1][https://github.com/rack-test/rack-test/commit/ece681de8ffee9d0caff30e9b93f882cc58f14cb](https://github.com/rack-test/rack-test/commit/ece681de8ffee9d0caff30e9b93f882cc58f14cb)

bmvo0sr5

bmvo0sr54#

我不能发送它作为json在我的情况下,因为我发送也发送文件作为multipart形式。我的解决方法是在数组中放入一个空字符串。

post '/posts', params: { ids: [""] }

相关问题