RSpec请求规范发布空数组

人气:71 发布:2023-01-03 标签: ruby-on-rails ruby http-post rspec rspec-rails

问题描述

我目前正在开发一个Rails中的API端点。如果我需要的数据无效,我希望确保具有正确错误状态的端点响应。我需要一组身份证。其中一个无效值是空数组。

有效

{ 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中的错误?

推荐答案

找到答案了!

问题

问题是在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,方法是使用'require 'json'将JSON gem添加到您的应用程序中,并使用.to_json附加参数散列。

并在RSpec请求中指定此请求的内容类型为JSON。

修改上面的示例:

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

18