expect(WebMock).to have_requested(:get, "any url")

735 Views Asked by At

I'm am adding Webmock stubbing to my tests.

Right now, I'm testing that a request was made, but I'd like to do so without matching the full url with all its parameters.

expect(WebMock).to have_requested(:get, "us-street.api.smartystreets.com")

Result:

Failure/Error: expect(WebMock).to have_requested(:get, "us-street.api.smartystreets.com")

   The request GET http://us-street.api.smartystreets.com/ was expected to execute 1 time but it executed 0 times
 
   The following requests were made:
 
   GET https://us-street.api.smartystreets.com/street-address?addressee&auth-id=#{@auth_id}&auth-token=#{@auth_token}&candidates=3&city&input_id&lastline&license=us-core-cloud&match=invalid&secondary&state&street=10%20Nocklyn%20Drave&street2&urbanization&zipcode=15237 with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/json', 'Host'=>'us-street.api.smartystreets.com', 'User-Agent'=>'smartystreets (sdk:[email protected])'} was made 1 time   

So it's failing the expectation because I didn't use the entire url in the second parameter.

I'm sure there must be some kind of wildcard symbol or something that will allow me to test whether any get request was made. I don't even care if any url is checked.

I've tried leaving the second argument blank

expect(WebMock).to have_requested(:get)

But that produces an ArgumentError.

Thanks in advance!

2

There are 2 best solutions below

0
aridlehoover On

According to the readme, you can match the URI with a /regex/, like this:

stub_request(:any, /example/)
0
Harry Wood On

You can use a regex to match just that hostname

expect(WebMock).to have_requested(:get, /us-street.api.smartystreets.com/)

Or a bit more of the path (Note %r syntax is nicer when there's any slashes involved)

expect(WebMock).to have_requested(:get, %r{https://us-street.api.smartystreets.com/street-address})

Or avoiding regex, you can add a "with" query matcher:

expect(WebMock).to have_requested(:get, "https://us-street.api.smartystreets.com/street-address").with(query: hash_excluding({}))

It's a little odd to be using hash_excluding and then exclude nothing, but this little trick tells webmock that any query params should match.