Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unit tests in Ruby for a REST API

I've written a basic REST API using sinatra.

Does anyone know the best way to write tests for it? I would like to do so using Ruby.

I've done my initial testing using curl. But I'd like to do something more robust. This is my first API - is there anything specific I should be testing?

like image 450
mscccc Avatar asked Jan 27 '11 02:01

mscccc


People also ask

Are API tests unit tests?

An API test is similar to a unit test with a setup (prepare data for calling the API method), a call to the API method and then checking of the results. The semantics may require multiple calls to the API, producing tests that have more than one step.

How do I run a test case in Ruby?

We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases.


1 Answers

The best way is a matter of opinion :) Personally, I like simple and clean. With tools like minitest, Watir and rest-client, you can put together a very simple test of both your REST interface as well as testing your web service through actual browsers (all major browsers are supported).

#!/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 the test cases by simply executing the script. There are many other testing systems and REST clients for Ruby which can be put to work in a similar way.

like image 114
David Weber Avatar answered Sep 28 '22 20:09

David Weber