5

I have an HTTParty request with response of the form:

#<HTTParty::Response:0x7fe078a60f58 
  parsed_response={"groups"=>
    [{"id"=>"11111", "name"=>"foo", "reference"=>nil},
     {"id"=>"22222", "name"=>"bar", "reference"=>nil}]
  }, 
  @response=#<Net::HTTPOK 200 OK readbody=true>, 
  @headers={
    "date"=>["Wed, 25 Nov 2015 13:05:27 GMT"], 
    "content-type"=>["application/xml; charset=utf-8"], 
    "content-length"=>["1752"], "connection"=>["close"],
    "status"=>["200 OK"], 
    "etag"=>["\"47f4a2f4b888491d07dc21b009e6f8a4\""],
    "x-frame-options"=>["DENY"], 
    "cache-control"=>["private, max-age=0, must-revalidate"],
    "p3p"=>["CP=\"CAO DSP COR CURa ADMa DEVa OUR IND PHY ONL UNI COM NAV INT DEM PRE\""]}
> 

I need to stub this request with web-mock in my Rspec test. This is what I did:

stub_request(
      :get, url
    )
      .with(:headers => {'Content-Type'=>'application/xml'})
      .to_return(
        :status => 200,
        :body => {
          "groups"=>[
            {"id"=>"11111", "name"=>"foo", "reference"=>nil},
            {"id"=>"22222", "name"=>"bar", "reference"=>nil}
          ]
        },
        :headers => {...})

But I'm getting the error:

WebMock::Response::InvalidBody: must be one of: [Proc, IO, Pathname, String, Array]. 'Hash' given

How can I write the body for my webmock stub to get a replica of what the response is?

Thanks.

x6iae
  • 4,074
  • 3
  • 29
  • 50

1 Answers1

5

Okay, I got it, by taking inspiration from the content-type of the response:

"content-type"=>["application/xml; charset=utf-8"]

Seeing that the content-type is xml, I decided to use xml formatting for my webmock as well, as follow:

stub_request(
      :get, url
    )
      .with(:headers => {'Content-Type'=>'application/xml'})
      .to_return(
        :status => 200,
        :body =>
          '<groups type="array">
            <group>
              <id>11111</id>
              <name>foo</name>
            </group>
            <group>
              <id>22222</id>
              <name>bar</name>
            </group>
          </groups>',
        :headers => {
          "content-type"=>["application/xml; charset=utf-8"]
        })

And everything worked fine.

x6iae
  • 4,074
  • 3
  • 29
  • 50