我是在另一个网站上上传图像文件,他们提供了相同的上传API。
文件上传过程分为2部分
- 创建图片 ID (POST)
- 上传图片(PUT)
当我创建图像 id 时,它会在响应中返回 id。为此,我添加了以下方法来实现此功能。
def create_image_id
response = create_via_api(data)
# we get response in the following format
# #<Net::HTTPCreated 201 Created readbody=true>
find_id_from_response(response)
end
def create_via_api(data)
access_token.post(IMAGE_CREATE_URL, data, 'Accept' => ACCEPT_HEADER)
end
# We are getting id from the response headers in the following format
# location: SITE_URL/imageResources/5ac2acb2
def find_id_from_response(response)
id = response.to_hash['location'].first
return unless id
id.split('/').last.chomp
end
现在我必须为 create_image_id 方法编写测试用例。
对于测试用例来说,与第三方 API 进行通信并不是一个好的做法。所以我对 POST 响应进行 stub ,说,
allow(Image).to receive(:find_id_from_response).and_return('1234')
所以它总是返回 id 为 123,以便我可以将测试用例编写为
expect(image. create_image_id).to eq 1234
如您所见,find_id_from_response 采用参数 (#)。
注意:这是响应的 header
[36] pry(#)> response.to_hash
{
"content-type"=>["text/plain"],
"x-frame-options"=>["SAMEORIGIN"],
"location"=>["www.example.com/imageResources/cd87b8ef"],
"vary"=>["Accept-Encoding"],
"cache-control"=>["max-age=0, no-cache"],
"pragma"=>["no-cache"],
"date"=>["Tue, 15 Nov 2016 12:01:56 GMT"],
"connection"=>["close"]
}
我尝试了以下
[28] pry()> Net::HTTPCreated.new(1, 201, 'Created')
=> #<Net::HTTPCreated 201 Created readbody=false>
[29] pry()> a = Net::HTTPCreated.new(1, 201, 'Created')
=> #<Net::HTTPCreated 201 Created readbody=false>
[30] pry()>)> a.to_hash
=> {}
它返回空哈希。那么如何 stub create_via_api 的响应呢?
请告诉我您需要的任何信息。
最佳答案
I don't think有一种简单的方法返回 http 响应对象。因此,您可以使用 rspec mocks
response_hash = {
"content-type"=>["text/plain"],
"x-frame-options"=>["SAMEORIGIN"],
"location"=>["www.example.com/imageResources/cd87b8ef"],
"vary"=>["Accept-Encoding"],
"cache-control"=>["max-age=0, no-cache"],
"pragma"=>["no-cache"],
"date"=>["Tue, 15 Nov 2016 12:01:56 GMT"],
"connection"=>["close"]
}
response_double = double
allow(response_double).to receive(:to_hash).and_return(response_hash)
allow(instance).to receive(:create_via_api).and_return(response_double)
expect(instance.create_via_api("data").to_hash['content-type']).to eq(["text/plain"])
另一个选择是使用记录和保存 api 调用进行测试的工具,并使用缓存的响应来执行所有后续测试,例如 vcr .
关于ruby-on-rails - Stub Net::HTTP在 rspec 中创建了响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611204/