如何正确复制HTTParty的响应主体请求对webmock存根的响应

时间:2015-11-25 14:00:50

标签: ruby-on-rails rspec httparty webmock

我有一个HTTParty请求,其回复形式为:

#<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\""]}
> 

我需要在我的Rspec测试中使用web-mock存根此请求。这就是我所做的:

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 => {...})

但是我收到了错误:

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

如何为我的webmock存根编写body以获取响应的副本?

感谢。

1 个答案:

答案 0 :(得分:2)

好的,我从响应的content-type中获取灵感,得到了它:

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

看到content-typexml,我决定对我的网络漫画使用xml格式,如下所示:

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"]
        })

一切正常。