Ruby TestUnit、VCR和HTTP API请求
我正在构建一个API包装器,并为此编写一些测试,我有几个问题 1) 如何为不存在数据的调用编写Ruby TestUnit、VCR和HTTP API请求,ruby,api,testunit,vcr,webmock,Ruby,Api,Testunit,Vcr,Webmock,我正在构建一个API包装器,并为此编写一些测试,我有几个问题 1) 如何为不存在数据的调用编写assert?例如,使用API按id查找成员,但用户还不存在。 2) 如何为测试PUT和DELETE请求编写assert 我已经掌握了测试GET和POST请求的方法,只是对其他两个动词没有把握 关于你的问题第1部分 对于不存在的数据,您有两种选择: 您可以提前创建数据,例如使用测试种子文件、夹具或工厂。对于具有更复杂数据安排的大型项目,我喜欢这种选择。我也喜欢这样的选择,因为这样可以更直观地看到数据 您
assert
?例如,使用API按id查找成员,但用户还不存在。2) 如何为测试
PUT
和DELETE
请求编写assert
我已经掌握了测试
GET
和POST
请求的方法,只是对其他两个动词没有把握 关于你的问题第1部分
对于不存在的数据,您有两种选择:
VCR.use_cassette('test_unit_example') do
response = Net::HTTP.get_response('localhost', '/', 7777)
assert_equal "Hello", response.body
end
如果是这样,您可以将HTTP get更改为put,如下所示:
uri = URI.parse(...whatever you want...)
json = "...whatever you want..."
req = Net::HTTP::Put.new(uri)
req["content-type"] = "application/json"
req.body = json
request(req)
HTTP删除也一样:
Net::HTTP::Delete.new(uri)
一篇好的博客文章是最好的http://www.rubyinside.com/nethttp-cheat-sheet-2940.html>Net::HTTP备忘单摘录于此:
# Basic REST.
# Most REST APIs will set semantic values in response.body and response.code.
require "net/http"
http = Net::HTTP.new("api.restsite.com")
request = Net::HTTP::Post.new("/users")
request.set_form_data({"users[login]" => "quentin"})
response = http.request(request)
# Use nokogiri, hpricot, etc to parse response.body.
request = Net::HTTP::Get.new("/users/1")
response = http.request(request)
# As with POST, the data is in response.body.
request = Net::HTTP::Put.new("/users/1")
request.set_form_data({"users[login]" => "changed"})
response = http.request(request)
request = Net::HTTP::Delete.new("/users/1")
response = http.request(request)