Using RSpec for Testing a Rest-Application

or

Using RSpec without any Ruby Knowledge

There are quite a lot of test frameworks out there. For C / C++ pieces I am using Boost. For testing the HTTP interface of one our software products I used phpunits. @moonbeamlabs pointed out to me that RSpec together with HTTParty provides a very nice setup for testing an application server with a HTTP interface. Even without any prior Ruby knowledge I gave it a try for a new open source project, AvocaodDB, and was surprised, how easy it was writting tests.

Basically you have to create a Gemfile describing the prerequisites:

source :rubygems
gem "httparty", "~> 0.8.1"
gem "rspec", "~> 2.8.0"

The second file sets up the connecting to the AvocadoDB and lives in avocadodb.rb:

class AvocadoDB
include HTTParty

base_uri 'http://localhost:8529'
format :json

def self.create_collection (name, wait_for_sync = true)
...
end

def self.drop_collection (name)
...
end

def self.log (args)
...
end
end

The method log is a small helper I wrote to generate examples for the manual from the test cases.

The last file “read-document_spec.rb” contains the test cases:

require 'rspec'
require './avocadodb.rb'

describe AvocadoDB do
prefix = "rest_read-document"

context "reading a document in a collection" do
context "error handling" do
before do
@cn = "UnitTestsCollectionBasics"
@cid = AvocadoDB.create_collection(@cn)
end

after do
AvocadoDB.drop_collection(@cn)
end

it "returns an error if handle is bad" do
cmd = "/document/123456"
doc = AvocadoDB.get(cmd)

doc.code.should eq(400)
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(503)
doc.parsed_response['code'].should eq(400)

AvocadoDB.log(:method => :get, :url => cmd, :result => doc, :output => "#{prefix}-bad-handle")
end
end
end
end

A full description of all the check functions can be found here. Put everything into a directory and execute

> rspec rest_read-document_spec.rb --format d

AvocadoDB
reading a document in a collection
error handling
returns an error if handle is bad
returns an error if collection identifier is unknown
returns an error if document handle is unknown
reading documents
create a document and read it
create a document and read it, use if-none-match

The examples can be found at GITHUB. I’m pretty sure there are thousand ways to make this more Ruby-like, but the point here is, that you can use rspec almost without any Ruby knowledge at all.