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

2.6k views Asked by At

I need to stub a request with 2 variations, and these are the example URLs from Amazon:

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

Right now, I have the regex validated via help from 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' })

UPDATES

After fixing the regex we are now trying to use the query string variables via stub request but it is not working. Thoughts anyone?

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' })

I am using Rails 5 and Rspec 3.5.

1

There are 1 answers

0
ckrailo On BEST ANSWER

After discussion, it turns out that we needed to search the body instead of the query params for this request.

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

Also, negative regex is hard. Instead, go for positive regex. :)