ruby-on-rails - RSpec 请求规范发布一个空数组

标签 ruby-on-rails ruby rspec http-post rspec-rails

我目前正在 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 block 内的参数中使用了一个空数组。

Controller 内的值

在我的 Controller 中,我正在获取数据

params.require(:vendor_district_ids)

值如下

<ActionController::Parameters {"vendor_district_ids"=>[""], "controller"=>"api/my_controller", "action"=>"create"} permitted: false>

vendor_district_ids 的值是一个包含空字符串的数组。当我用 postman 发帖时,我没有相同的值。

postman 的值(value)

如果我发帖

{ "vendor_district_ids": [] }

Controller 将接收

<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

解决方案

将您的参数转换为 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

关于ruby-on-rails - RSpec 请求规范发布一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51396194/

相关文章:

ruby - 如何避免在解码文件时出现 UndefinedConversionError?

ruby-on-rails - 如何测试 ActiveSupport::TaggedLogging

ruby-on-rails - Rails 4.2 片段缓存不起作用

ruby-on-rails - 如何在RestClient获取请求头中传递参数并访问 Controller 中的参数

arrays - 按索引映射两个数组

ruby-on-rails - 具有相同代码的 2 个测试之间的 Rspec 不一致结果

ruby-on-rails - 从字符串编译 ERB 代码时出错

javascript - 快速连续发生的多个发布请求

ruby-on-rails - created_at字段有时变为nil

ruby - 安装 el capitan 后 compass 不工作