Webmock not responding to stub request with query
Asked Answered
G

1

6

I'm working on a Ruby on Rails gem and I'm trying webmock because I need to interact (and test) an external API not under my control.

So, here is the snippet which is in before(:each) because I was stubbing it there:

before do
  uri = URI.join(client.class.base_uri, DataComApi::ApiURI.search_contact).to_s
  stub_request(
    :get,
    uri
  ).with(
    query: hash_including({
      'pageSize' => 0,
      'offset'   => 0
    })
  ).to_return(
    body: FactoryGirl.build(
      :data_com_search_contact_response,
      totalHits: 0
    ).to_json
  )
  # DEBUG
  require 'httparty'
  HTTParty.get(
    uri,
    {
      query: {
        offset:   0,
        pageSize: 0
      }
    }
  )
end

And here you can see the console output of rspec command:

  3) DataComApi::Client#search_contact returns instance of SearchContact
     Failure/Error: HTTParty.get(
     WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: GET https://www.jigsaw.com/rest/searchContact.json?offset=0&pageSize=0

       You can stub this request with the following snippet:

       stub_request(:get, "https://www.jigsaw.com/rest/searchContact.json?offset=0&pageSize=0").
         to_return(:status => 200, :body => "", :headers => {})

       registered request stubs:

       stub_request(:get, "https://www.jigsaw.com/rest/searchContact.json with query params hash_including({"offset"=>0, "pageSize"=>0})")

       ============================================================
     # ./spec/models/client_spec.rb:65:in `block (3 levels) in <top (r

If I remove the :query key both on HTTParty.get and in stub_request, it works, but I need those query keys and values to test the API.

I tested even by replacing in stub_request, uri with /searchContact.json/ but had same issue.

Here you can find a GIST

Graduate answered 7/2, 2014 at 2:22 Comment(1)
Just a note. If you have params like this filter[xyz]=1, you should mock with with(query: hash_including(filter: { xyz: 1 }))Matherne
G
6

I solved it by myself, looks like is a bug: you must stub the request in webmock with 'query' (a String) because Symbol doesn't work. The worst part is that symbols are allowed inside the query hash.

I reported it as a bug: https://github.com/bblimke/webmock/issues/366

Edit I was wrong, looks like the only way is: use query key as a symbol, but values of the hash must be strings, otherwise it won't be found (params in query are always strings)

Graduate answered 7/2, 2014 at 2:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.