ruby – 如何測試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執行
ofollow,noindex" target="_blank">JSON.parse 將JSON字串解析為rubyhash
如果您使用的是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