如何使用嵌套数据编写可运行的Webmock存根?

时间:2018-12-25 08:43:54

标签: webmock

我正在尝试编写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

1 个答案:

答案 0 :(得分:0)

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

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