如何使用嵌套数据编写功能性 Webmock 存根?

How to write functioning Webmock stubs with nested data?

我正在尝试编写 rspec 测试。其中一些必须存根调用外部服务。

其中一些调用发送嵌套数据,而这些数据似乎从未被 Webmock 正确处理。

describe 'calc' do
  before do
    stub_request(:any, url).with(body: hash_including(operation: 'calc'))
  end

  it 'works' do
    request_data = { sale_type: 'money', cover_type: 'money', 
                     region: 'rf', period: 9,
                     adults: 600, children: 750, mice: 500 }

    # This thing makes a HTTP request:
    MiteService.new(login_params).calc(request_data)

    expected_body = { operation: 'calc', product: 'mite3', 
                      sessionID: session, data: request_data }
    expect(WebMock).to have_requested(:post, url).with(body: expected_body)
  end
end

本次测试有望通过。服务发出的 http 调用似乎是正确的,但 Webmock 无法读取任何嵌套数据(在这种情况下,它位于正文的 data 部分)。

1) MiteService API calls calc works
 Failure/Error: expect(WebMock).to have_requested(:post, url).with(body: expected_body)

   The request POST http://example.com/api with body {"data"=>{"sale_type"=>"money", "cover_type"=>"money", "region"=>"rf", "period"=>9, "adults"=>600, "children"=>750, "mice"=>500}, "operation"=>"calc", "product"=>"mite3", "sessionID"=>"123"} was expected to execute 1 time but it executed 0 times

   The following requests were made:

   <...>
   POST http://example.com/api with body 'operation=calc&product=mite3&sessionID=123&data=%7B%3Asale_type%3D%3E%22money%22%2C+%3Acover_type%3D%3E%22money%22%2C+%3Aregion%3D%3E%22rf%22%2C+%3Aperiod%3D%3E9%2C+%3Aadults%3D%3E600%2C+%3Achildren%3D%3E750%2C+%3Amice%3D%3E500%7D' with headers {'Accept'=>'*/*', 'Content-Type'=>'application/x-www-form-urlencoded', 'Date'=>'Tue, 25 Dec 2018 08:20:32 GMT', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.4.1 (2017-03-22))'} was made 1 time

通过将字段转换为示例规范中的 json 使其适用于此示例。

expect(WebMock).to have_requested(:post, url).with(body: expected_body.to_json)