[英]How to test a JSON REST API
我是红宝石的新手(第一天使用红宝石)所以请原谅任何新手问题和缺乏理解。
我正在尝试验证对http标注的响应。
例如,假设端点如下:
https://applicationname-api-sbox02.herokuapp.com
并且,我正在尝试通过发送这样的get请求来验证用户:
get_response = RestClient.get( "https://applicationname-api-sbox02.herokuapp.com/api/v1/users",
{
"Content-Type" => "application/json",
"Authorization" => "token 4d012314b7e46008f215cdb7d120cdd7",
"Manufacturer-Token" => "8d0693ccfe65104600e2555d5af34213"
}
)
现在,我想验证响应并执行以下操作: - 解析响应以确保它是有效的JSON - 执行一些验证并验证JSON是否具有正确的数据(例如,验证id == 4) - 如果出现错误遇到,使用'raise'方法引发异常。
在我第一次虚弱的尝试中,我尝试了以下方法:
puts get_response.body
if get_response.code == 200
puts "********* Get current user successful"
else
puts "Get current user failed!!"
end
现在,这返回了获取当前用户的成功,但是如何实际解析json,验证正确的id,并在发生错误时引发异常?
写一个测试,而不是提出异常。
一个简单的方法,使用std lib中的json解析器和单元测试框架:
require 'minitest/autorun'
require 'rest_client'
require 'json'
class APITest < MiniTest::Unit::TestCase
def setup
response = RestClient.get("https://applicationname-api-sbox02.herokuapp.com/api/v1/users",
{
"Content-Type" => "application/json",
"Authorization" => "token 4d012314b7e46008f215cdb7d120cdd7",
"Manufacturer-Token" => "8d0693ccfe65104600e2555d5af34213"
}
)
@data = JSON.parse response.body
end
def test_id_correct
assert_equal 4, @data['id']
end
end
用ruby $filename
执行
JSON.parse将JSON字符串解析为ruby 哈希
如果您使用的是ruby 1.8,则需要安装json gem并安装minitest gem ,或者切换到较旧的testunit API。 如果选择后者,则需要更改require 'minitest/autorun'
- > require 'minitest/autorun'
require 'test/unit'
和MiniTest::Unit::TestCase
- > Test::Unit::TestCase
我参加聚会的时间有点晚了,但我最近为此目的共同创建了一个名为Airborne
的rspec驱动框架。 看看: https : //github.com/brooklynDev/airborne
这是我们的规范中的一个例子,所以你可以看到我们如何测试json api:
it 'returns charge' do
get "/charges/#{charge.id}", '', headers
expect(response.status).to eq(200)
expect(response).to match_response_schema(:charge)
expect(response).to match_json(<<-JSON)
{
"id":"{id}",
"email": "{email}",
"ip": "127.0.0.1",
"amount": 10500,
"state": "captured",
"captured_amount": 10500,
}
JSON
end
让我们仔细看看
match_response_schema(:charge)
这个匹配器检查我们得到的json是否一般有效。 我们使用json-schema (json模式验证器)。 来自Thoughtbot的家伙有详细的指南如何使用json架构验证器并在此博客文章中创建自己的匹配器。
了解JSON Schema是我获得有关如何为JSON文档创建模式的大量有用信息的地方。
match_json
这是我们自己的匹配器,我们最近发布了match_json gem。 使用它,您可以测试json的结构和值。 以下是此匹配器的两个重要功能:
解析json可以使用json gem完成: http : //flori.github.com/json/
解析的json是通过键/值访问的,就像在javascript中一样。 您可以轻松验证值并有条件地引发错误。
引发错误的方式如下:
raise "the ID was #{id} instead of 4"
编写单元测试可以使用Test :: Unit - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/test/unit/rdoc/Test/Unit.html完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.