2

I’m using Rails 6 and web mock 3.14.0. I mock a particular outbound request like so

stub_request(:post, "https://#{APP_CONFIG.vendor[Rails.env][:api].domain}/api/start“).
     with(
       headers: {
      'Accept'=>'application/json',
      'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
      'Content-Length'=>'65',
      'Content-Type'=>'application/json',
      'Host'=>APP_CONFIG.tci[Rails.env][:api].domain,
      'User-Agent'=>'rest-client/2.1.0 (darwin20.6.0 x86_64) ruby/2.7.1p83'
       }).
     to_return(status: 200, body: resp.to_json, headers: {})

The issue is if the ‘User-Agent’ header differs, the mock doesn’t take, and instead I get an error complaining about an unregistered request and stating that I need to set up my mock like so

stub_request(:post, "https://#{APP_CONFIG.vendor[Rails.env][:api].domain}/api/start“).
     with(
       headers: {
      'Accept'=>'application/json',
      'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
      'Content-Length'=>'65',
      'Content-Type'=>'application/json',
      'Host'=>APP_CONFIG.tci[Rails.env][:api].domain,
      'User-Agent'=>'rest-client/2.1.0 (linux-gnu x86_64) ruby/2.7.1p83'
       }).
     to_return(status: 200, body: resp.to_json, headers: {})

Note the header contains “linux” instead of “Darwin”. How do I write my web mock to ignore the ‘User-Agent’ header, or at least write some kind of regular expression to capture any type of user-agent header?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

1

Updated answer: When you write the User-Agent header like this, it will match both "darwin20.6.0 x86_64" and "linux_gnu x86_64". It will match anything inside the parenthesis.

...
'User-Agent'=>/rest-client\/2.1.0\s\(.*\)\sruby\/2.7.1p83/
...
Gerald Spreer
  • 413
  • 4
  • 11
  • The issue is I'd be happy to ignore the User-Agent header entirely, but there are other headers I need to verify exactly. If I leave only the User-Agent header off, things still seem to fail. – Dave Dec 21 '21 at 15:50
  • @Dave I Have updated my answer. See if this works for you. Here are more details about using regex in webmock. https://github.com/bblimke/webmock#matching-request-body-and-headers-against-regular-expressions – Gerald Spreer Dec 22 '21 at 17:01