3

我有一个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

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

谢谢。

4

1 回答 1

3

好的,我明白了,从content-type响应中获取灵感:

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

看到content-typeis xml,我决定也xml为我的 webmock 使用格式,如下所示:

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

一切正常。

于 2015-11-25T14:59:41.277 回答