book a call

estimate project

The belighted Blog

With a little help from Json_spec and Rack::Test

by Yannick S., on 15 August 2012

Last week, I had to design a little json API. It had to be fast and furious. For that purpose, we made it with Sinatra.

The point was we didn’t want to make a single file Sinatra app. We made a small reusable skeleton of a Sinatra app using ActiveRecord to store the small amount of objects.

It had to be full stack tested. For that we used Rspec and Rack Test for the API testing part.

You can easily check the response payload with something like json_spec. It’s so easy to use.

Here is a small example:

 it 'get the greeting' do 
 get "/api/#{}" 
 last_response.should be_ok 
 last_json.should have_json_path 'name' 

The last_json object is simply a method defined into the spec_helper.rb file which looks like this:

ENV['RACK_ENV'] = 'test' 
# Load the Sinatra app 
require File.join( File.dirname( FILE ), '..', 'server' ) 

require 'rspec' 
require 'rack/test' 
require 'json_spec' 

set :environment, :test 

RSpec.configure do |conf| 
 conf.include Rack::Test::Methods 
 conf.include JsonSpec::Helpers 
 #all your others informations 

 last_json last_response.body 

def app 

With json_spec, you have access to some great matchers like be_json_eq, have_json_path orhave_json_size which help a lot doing things like have_json_size(0).at_path("friends"). The doc is really helpful for that.

With Rack::Test, you have a lot of helpers like the classic http methods. And access to an object last_response which contains the http response of the last request.

All that helped to get a working API in a couple of days. For more information about the sinatra skeleton, I recommend you another blog post I wrote on my own blog or don’t hesitate to ask as many questions as you want!

Topics:      Under the hood

What is SaaS?

Everything You Need to Know About Moving to a SaaS Model.

Get the guide now >

Subscribe to Updates