Ruby Webmock未正确注册我的请求存根

Ruby Webmock未正确注册我的请求存根,ruby,rspec,mocking,request,stubbing,Ruby,Rspec,Mocking,Request,Stubbing,我正在注册一个请求存根,如下所示: url = "http://www.example.com/1" stub_request(:get, url). with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n", headers: { 'Accept' => 'a

我正在注册一个请求存根,如下所示:

url = "http://www.example.com/1"
stub_request(:get, url).
  with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
       headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       }).
  to_return(status: 200, body: '', headers: {})
请注意,返回的
部分缺失

我尝试用空字符串替换
正文
标题,请求存根已正确注册,但我的规范仍将失败,因为它们期望正文中的值而不是空字符串。所以,我给body赋值是非常重要的

在我的规范中,我将此方法称为:

def find(id)
  require 'net/http'
  http = Net::HTTP.new('www.example.com')
  headers = {
    "X-TrackerToken" => "12345",
    "Accept"         => "application/xml",
    "Content-type"   => "application/xml",
    "User-Agent"     => "Ruby"
  }
  parse(http.request(Net::HTTP::Get.new("/#{id}", headers)).body)
end
你知道为什么会这样吗


谢谢。

问题在于,存根将GET请求与非空的
\n\n 1\n\n
正文相匹配,但是当您发出请求时,您没有包含任何正文,因此它找不到存根

我想你对这里的身体感到困惑。带有
方法参数的
中的主体是您正在发出的请求的主体,而不是响应的主体。您可能需要这样一个存根:

url = "http://www.example.com/1"
stub_request(:get, url).
  with(headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       }).
  to_return(status: 200,
            body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
            headers: {})
url=”http://www.example.com/1"
存根请求(:get,url)。
带有(标题:{
'接受'=>'应用程序/xml',
'内容类型'=>'应用程序/xml',
“用户代理”=>“Ruby”,
“X-Trackertoken”=>“12345”
}).
返回(状态:200,
正文:“\n\n 1\n\n”,
标题:{})

你能发布相关的规范代码吗?@shioyama,在我的规范中,我调用这个方法:
def find(id)require'net/http'http::net.new('www.example.com')headers={“X-TrackerToken”=>“12345”,“Accept”=>“application/xml”,“Content type”=>“application/xml”“用户代理”=>“Ruby”}parse(http.request(Net::http::Get.new(“/{id}”,headers)).body)end
我不明白,如果在实际请求中没有传递一个body,为什么要在存根的
中包含
body
。在我看来,解决方案似乎是只需取出存根的
中带有
主体
,然后将该值放入
主体的
部分以返回
。还是我搞错了?
url = "http://www.example.com/1"
stub_request(:get, url).
  with(headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       }).
  to_return(status: 200,
            body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
            headers: {})