我正在注册请求存根,如下所示:
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
标头,请求存根已正确注册,但我的规格仍然会失败,因为他们期望除了空字符串以外的其他值。因此,为身体赋值是非常重要的。
在我的规范中,我称这种方法为:
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
关于为什么会发生这种情况的任何想法?
感谢。
答案 0 :(得分:6)
问题是你的存根正在将GET请求与非<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n
的空体匹配,但是当你发出请求时你没有包含任何正文,所以它找不到存根。
我觉得你对这里的身体感到困惑。 with
方法参数中的正文是您正在创建的请求的正文,而不是响应的正文。你可能想要的是这样的存根:
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: {})