首页 > 解决方案 > 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

标签: ruby-on-railsrubyrspechttp-postrspec-rails

解决方案


找到了答案!

问题

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

推荐阅读