2011-01-27 97 views
13

我已經使用sinatra編寫了基本的REST API。在Ruby中爲REST API編寫單元測試

有誰知道編寫測試的最佳方法嗎?我想用Ruby來做。

我已經使用curl完成了我的初始測試。但我想做更強大的事情。這是我的第一個API - 有什麼具體的我應該測試?

+0

curl有什麼問題?你可以編寫運行curl的單元測試,並檢查你找回你期望的內容 - 標題和正文。否則你可能會考慮像http://watir.com/這樣的東西? – iain 2011-01-27 02:45:19

+2

@lain:使用Watir或捲曲不是單元測試。一般來說,這是一項功能或集成測試。 – Chamnap 2011-01-27 02:56:38

+1

單元測試正在測試代碼中*的功能單元,而不是從外部測試。使用curl或任何類似的代碼都不在代碼中。我們需要更多地瞭解您的Web服務正在完成什麼來幫助您進行單元測試。 – 2011-01-27 03:04:14

回答

4

你可以看看這種方法http://anthonyeden.com/2013/07/10/testing-rest-apis-with-cucumber-and-rack.html

雖然很多人可能會說,用黃瓜確實是更多的應用或驗收測試,而不是單元測試,它包含一個方法來創建HTTP標頭和形成HTTP請求,我猜可能是你被卡住的地方?

就個人而言,我沒有問題,因爲如果你真的要單元測試API,你可能不得不模擬API可能與之交談的任何代碼單元(例如,但是你堅持數據)

看到,因爲我是一個QA傢伙不是dev的,我會用黃瓜並在該水平測試它非常高興,但我也非常感激,當開發者的單元測試,因此,儘管你可以使用rSpec而不是Cuke,可能對'機架測試'的提示對你正在努力完成的任務有用。

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 

通過簡單地執行腳本運行測試用例。 Ruby還有很多其他測試系統和REST客戶端,可以用類似的方式工作。