在Ruby中编写单元测试用于REST API

msc*_*ccc 13 ruby api unit-testing

我使用sinatra编写了一个基本的REST API.

有谁知道为它编写测试的最佳方法?我想用Ruby做到这一点.

我使用curl完成了我的初始测试.但我想做一些更强大的事情.这是我的第一个API - 有什么具体的我应该测试吗?

Dav*_*ber 6

最好的方法是意见问题:)就个人而言,我喜欢简单干净.使用minitest,Watirrest-client等工具,您可以对REST接口进行非常简单的测试,并通过实际浏览器测试您的Web服务(支持所有主流浏览器).

#!/usr/bin/ruby
#
# Requires that you have installed the following gem packages: 
# json, minitest, watir, watir-webdrive, rest-client
# To use Chrome, you need to install chromedriver on your path

require 'rubygems'
require 'rest-client'  
require 'json'
require 'pp'
require 'minitest/autorun'
require 'watir'
require 'watir-webdriver'

class TestReportSystem < MiniTest::Unit::TestCase
   def setup
      @browser = Watir::Browser.new :chrome # Defaults to firefox. Can do Safari and IE too.
      # Log in here.....
   end

   def teardown
      @browser.close
   end

   def test_report_lists   # For minitest, the method names need to start with test
      response = RestClient.get 'http://localhost:8080/reporter/reports/getReportList'
      assert_equal response.code,200
      parsed = JSON.parse response.to_str
      assert_equal parsed.length, 3 # There are 3 reports available on the test server
   end

   def test_on_browser
      @browser.goto 'http://localhost:8080/reporter/exampleReport/simple/genReport?month=Aug&year=2012'
      assert(@browser.text.include?('Report for Aug 2012'))
   end
end
Run Code Online (Sandbox Code Playgroud)

只需执行脚本即可运行测试用例.Ruby有许多其他测试系统和REST客户端,可以以类似的方式工作.


Chu*_*den 4

您可能会看看这种方法 http://anthonyeden.com/2013/07/10/testing-rest-apis-with-cucumber-and-rack.html

尽管很多人可能会说使用 Cucumber 实际上更多的是应用程序或验收测试,而不是单元测试,但它确实包含一种创建 HTTP 标头和形成 http 请求的方法,我猜这可能是您陷入困境的地方?

就我个人而言,我对此没有问题,因为如果您真的要对 API 进行单元测试,您可能必须模拟 api 可能正在与之通信的任何代码单元(例如,无论您如何保存数据)

鉴于我是一个 QA 人员而不是开发人员,我非常乐意使用 Cucumber 并在该级别进行测试,但我也非常欣赏开发人员进行单元测试时的做法,因此虽然您可能会使用 rSpec 而不是 Cuke,但也许“机架测试”的提示将对您想要完成的任务很有用。

  • 更正了链接。其他一些善意的人试图进行编辑,但白痴审稿人显然认为这个改变太小了。亲自将无效链接更正为有效链接对我来说似乎并不小。 (3认同)