Chris
Chris

Reputation: 449

Using webmock to stub partial headers

I am creating tests using webmock. I want to test that a particular header field is set, but I don't care about other header fields. When I use this:

stub_request(:get, "https://myhost.com/api").
  with(:headers => {:user_agent => 'Custom user agent'}).
  to_return(:status => 200, :body => '')

I get an error because I am not stubbing all the headers:

Unregistered request: GET https://myhost.com/api with headers {'Accept'=>'application/json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Custom user agent'}

You can stub this request with the following snippet:

stub_request(:get, "https://myhost.com/api").
  with(:headers => {'Accept'=>'application/json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Custom user agent'}).
  to_return(:status => 200, :body => "", :headers => {})

I don't care about the Accept and Accept-Encoding headers - how do I stub so they are ignored?

Upvotes: 3

Views: 4202

Answers (2)

Tan Duong
Tan Duong

Reputation: 1561

Web mock does partial matching by default. In your case, the :user_agent key is a symbol which won't match the string 'User-Agent'. Converting to a string should work:

'User-Agent'=>'Custom user agent'

Upvotes: 3

Kristiina
Kristiina

Reputation: 533

You can use hash_including:


     stub_request(:get, "https://myhost.com/api").
       with(:headers => hash_including({:user_agent => 'Custom user agent'})).
       to_return(:status => 200, :body => '')
    

Upvotes: 1

Related Questions