stub_request 正则表达式,其中 url 参数存在且不存在于 Rspec

stub_request regex where url params exists and does not exist in Rspec

我需要存根具有 2 个变体的请求,这些是来自 Amazon 的示例 URL:

https://mws.amazonservices.jp/Orders/2013-09-01
  ?AWSAccessKeyId=0PB842EXAMPLE7N4ZTR2
  &Action=ListOrders
  &MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE
  &MarketplaceId.Id.1=A1VC38T7YXB528
  &FulfillmentChannel.Channel.1=MFN
  &PaymentMethod.Method.1=COD
  &PaymentMethod.Method.2=Other
  &OrderStatus.Status.1=Unshipped
  &OrderStatus.Status.2=PendingAvailability
  &SellerId=A2NEXAMPLETF53
  &Signature=ZQLpf8vEXAMPLE0iC265pf18n0%3D
  &SignatureVersion=2
  &SignatureMethod=HmacSHA256
  &LastUpdatedAfter=2013-08-01T18%3A12%3A21
  &Timestamp=2013-09-05T18%3A12%3A21.687Z
  &Version=2013-09-01

https://mws.amazonservices.jp/Orders/2013-09-01
  ?AWSAccessKeyId=0PB842EXAMPLE7N4ZTR2
  &Action=ListOrdersByNextToken
  &MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE
  &SellerId=A2986ZQ066CH2F
  &Signature=ZQLpf8vEXAMPLE0iC265pf18n0%3D
  &SignatureVersion=2
  &SignatureMethod=HmacSHA256
  &NextToken=2YgYW55IGNhcm5hbCBwbGVhc3VyZS4%3D
  &Timestamp=2013-09-05T18%3A12%3A21.687Z
  &Version=2013-09-01

现在,我通过 ckrailo but it appears stub_request is not accepting the regex? The regex has been validated via rubular 的帮助验证了正则表达式。

stub_request(:any, %r{/^.*amazonservices.com.*(&Action=ListOrders&).*$/}).to_return(body: order_fixture_with_pages, status: 200, headers: { 'Content-Type': 'text/xml' })
stub_request(:any, %r{/^.*amazonservices.com.*(&Action=ListOrdersByNextToken&).*$/}).to_return(body: order_fixture_no_pages, status: 200, headers: { 'Content-Type': 'text/xml' })

更新

修复正则表达式后,我们现在尝试通过存根请求使用查询字符串变量,但它不起作用。有人有想法吗?

stub_request(:any, /.*amazonservices.com.*/).
with(:query => hash_including({"Action" => 'ListOrders'})).
to_return(body: order_fixture_with_pages, status: 200, headers: { 'Content-Type': 'text/xml' })

我正在使用 Rails 5 和 Rspec 3.5。

经过讨论,发现我们需要为这个请求搜索正文而不是查询参数。

before do
  stub_request(:any, /.*amazonservices.com.*/).
  with(body: /^.*(&Action=ListOrders&).*$/).
  to_return(body: order_fixture_with_pages, status: 200, headers: { 'Content-Type': 'text/xml' })

  stub_request(:any, /.*amazonservices.com.*/).
  with(body: /^.*(&Action=ListOrdersByNextToken&).*$/).
  to_return(body: order_fixture_no_pages, status: 200, headers: { 'Content-Type': 'text/xml' })
end

此外,negative regex is hard。相反,选择正则表达式。 :)