ruby – 如何测试JSON REST API

栏目: Ruby · 发布时间: 5年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/13955233/how-to-test-a-json-rest-api

我是全新的红宝石(第一天使用红宝石),所以请原谅任何新手问题和缺乏理解.

我试图验证对http呼叫的响应.

例如,假设端点如下:

https://applicationname-api-sbox02.herokuapp.com

而且,我正在尝试通过发送这样的获取请求来验证用户:

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 hash

Getting started with minitest

如果您使用的是 ruby 1.8,则需要安装 json gem 并安装 minitest gem ,或者切换到较旧的testunit API.如果您选择后者,则需要更改require’minitest / autorun’ – >需要’test / unit’和MiniTest :: Unit :: TestCase – >测试::单位:: TestCase的

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/13955233/how-to-test-a-json-rest-api


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Hard Thing About Hard Things

The Hard Thing About Hard Things

Ben Horowitz / HarperBusiness / 2014-3-4 / USD 29.99

Ben Horowitz, cofounder of Andreessen Horowitz and one of Silicon Valley's most respected and experienced entrepreneurs, offers essential advice on building and running a startup—practical wisdom for ......一起来看看 《The Hard Thing About Hard Things》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码