我正在注册一个请求存根,如下所示:
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: {})
出于某种原因,当我运行时bundle exec rspec spec
,我的规格说明该请求尚未注册。注册的存根是这个,
stub_request(:get, "http://www.example.com/1").
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
部分丢失
我尝试用body
空字符串替换标头,请求存根已正确注册,但我的规范仍然会失败,因为他们期望正文中的值不是空字符串。因此,为 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
关于为什么会发生这种情况的任何想法?
谢谢。