ruby 如何测试 JSON REST API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13955233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:36:42  来源:igfitidea点击:

How to test a JSON REST API

ruby

提问by Dman100

I'm brand new to ruby (first day working with ruby) so please forgive any novice questions and lack of understanding.

我是 ruby​​ 的新手(第一天使用 ruby​​)所以请原谅任何新手问题和缺乏理解。

I'm trying to validate the responses to http callouts.

我正在尝试验证对 http 标注的响应。

For example, let's say the endpoint is the following:

例如,假设端点如下:

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

And, I'm trying to authenticate a user by sending a get request like this:

而且,我正在尝试通过发送这样的 get 请求来对用户进行身份验证:

get_response = RestClient.get( "https://applicationname-api-sbox02.herokuapp.com/api/v1/users", 
                    {
                        "Content-Type" => "application/json",
                        "Authorization" => "token 4d012314b7e46008f215cdb7d120cdd7",
                        "Manufacturer-Token" => "8d0693ccfe65104600e2555d5af34213"
                    }
                ) 

Now, I want to validate the response and do the following: - parse the response to ensure that it is valid JSON - do some validation and verify the JSON has the correct data (verify that id == 4 for example) - if an error is encountered, raise an exception using the 'raise' method.

现在,我想验证响应并执行以下操作: - 解析响应以确保它是有效的 JSON - 进行一些验证并验证 JSON 具有正确的数据(例如验证 id == 4) - 如果出现错误遇到,使用 'raise' 方法引发异常。

In my first feeble attempt I tried the following:

在我第一次微弱的尝试中,我尝试了以下方法:

puts get_response.body
if get_response.code == 200
puts "********* Get current user successful"
else
puts "Get current user failed!!"
end 

Now, this returned that getting the current user was successful, but how do I actually parse the json, verify the correct id, and raise an exception if an error occurred?

现在,这返回获取当前用户已成功,但是我如何实际解析 json,验证正确的 id,并在发生错误时引发异常?

回答by ireddick

Instead of raising an exception, write a test.

与其引发异常,不如编写一个测试。

A straightforward approach, using the json parser and unit test framework from the std lib:

一种简单的方法,使用 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

Execute with ruby $filename

执行 ruby $filename

JSON.parseparses a JSON string into a ruby hash

JSON.parse将 JSON 字符串解析为 ruby哈希

Getting started with minitest

开始使用 minitest

If you are using ruby 1.8, you'll need to install the json gemand either install the minitest gem, or switch to the older testunit API. If you choose the latter, then you'll need to change require 'minitest/autorun'-> require 'test/unit'and MiniTest::Unit::TestCase-> Test::Unit::TestCase

如果您使用 ruby​​ 1.8,则需要安装json gem并安装minitest gem或切换到旧版 testunit API。如果选择后者,则需要更改require 'minitest/autorun'->require 'test/unit'MiniTest::Unit::TestCase->Test::Unit::TestCase

回答by BFree

I'm a little late to the party, but I recently co-created an rspec driven framework called Airbornefor just this purpose. Check it out: https://github.com/brooklynDev/airborne

我参加聚会有点晚了,但我最近共同创建了一个 rspec 驱动的框架Airborne,专门为此目的而调用。看看:https: //github.com/brooklynDev/airborne

回答by Gabriel Pavel

here is an example from our specs so you can see how we test json api:

这是我们规范中的一个示例,因此您可以看到我们如何测试 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

Lets look at it closely

让我们仔细看看

  1. match_response_schema(:charge)
  1. match_response_schema(:charge)

This matcher checks that json we get in response is in general valid. We use json-schema(json schema validator) for it. Guys from Thoughtbot have a detailed guidehow to use json schema validator and create own matcher in this blog post.

这个匹配器检查我们在响应中得到的 json 通常是有效的。我们为此使用json-schema(json 模式验证器)。来自 Thoughtbot 的人在这篇博文中有详细的指南如何使用 json 模式验证器和创建自己的匹配器。

Understanding JSON Schemais where I got a lot of useful information on how to create schemas for JSON documents.

了解 JSON Schema是我获得很多关于如何为 JSON 文档创建模式的有用信息的地方。

  1. match_json
  1. match_json

This is our own matcher and we have released match_jsongem recently. Using it you can test structure and values of your json. Here are two great features of this matcher:

这是我们自己的匹配器,我们最近发布了match_jsongem。使用它,您可以测试 json 的结构和值。这是此匹配器的两个重要功能:

  • if you don't know exact values, you can use patterns like {id}, {uuid} {date_time}, etc. we have predefined patterns but you can add your own too.
  • you get clear failure message what is wrong with your json e.g. "5" was not found in " > array":[1,2,3]
  • 如果您不知道确切的值,您可以使用 {id}、{uuid}、{date_time} 等模式。我们有预定义的模式,但您也可以添加自己的模式。
  • 您会收到明确的失败消息,您的 json 有什么问题,例如在“> 数组”中找不到“5”:[1,2,3]

回答by AJcodez

Parsing json can be done with the json gem: http://flori.github.com/json/

解析 json 可以使用 json gem 完成:http: //flori.github.com/json/

Parsed json is accessed through key/value just like in javascript. You can easily verify the values and conditionally raise errors.

解析后的 json 是通过键/值访问的,就像在 javascript 中一样。您可以轻松验证这些值并有条件地引发错误。

Raising errors is done like so:

引发错误是这样完成的:

raise "the ID was #{id} instead of 4"

And writing unit tests can be done with Test::Unit - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/test/unit/rdoc/Test/Unit.html

可以使用 Test::Unit 编写单元测试 - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/test/unit/rdoc/Test/Unit.html