webmock icon indicating copy to clipboard operation
webmock copied to clipboard

Failures shouldn't recommend mocking the "User-Agent" header.

Open abscondment opened this issue 8 years ago • 4 comments

Some libraries (e.g. Twilio) include platform and Ruby version in their User-Agent. webmock suggests stubbing requests Twilio requests like this:

You can stub this request with the following snippet:
stub_request(:get, "https://api.twilio.com/2010-04-01/Accounts/id/AvailablePhoneNumbers/US/Local.json").
  with(:headers => {'Accept'=>'application/json', 'Accept-Charset'=>'utf-8', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'twilio-ruby/4.5.0 (ruby/x86_64-darwin15 2.2.4-p230)'}).
  to_return(:status => 200, :body => "", :headers => {})

This is the problematic part, and it's easily missed:

'User-Agent'=>'twilio-ruby/4.5.0 (ruby/x86_64-darwin15 2.2.4-p230)'

If one includes that header in the stub, tests will pass locally. travis et al will fail opaquely because they are (very likely) testing different versions on a different platform.

Instead of blindly pumping out all headers in this helpful error message, I'd like to propose deleting whatever User-Agent is set. I'd be happy to provide a patch if this sounds desirable.

abscondment avatar Mar 12 '16 00:03 abscondment

:+1: good idea. Please do submit a pull request.

bblimke avatar Mar 12 '16 23:03 bblimke

@abscondment , did you get any solution for that?

everaldo avatar Nov 09 '18 12:11 everaldo

I decided to match User-Agent agains a regular expression, as explained here

https://github.com/bblimke/webmock#matching-request-body-and-headers-against-regular-expressions

everaldo avatar Nov 09 '18 13:11 everaldo

I faced similar issue, removed header from stub and it worked fine.

naufil50 avatar Aug 01 '23 08:08 naufil50