<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=706355809571598&amp;ev=PageView&amp;noscript=1">
Free Assessment
Estimate Project
Menu
Estimate Project

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:

1
2
3
4
5
6
7
 ...
 it 'get the greeting' do
 get "/api/#{person.name}"
 last_response.should be_ok
 last_json.should have_json_path 'name'
 end
 ...

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
end

def last_json
 last_response.body
end

def app
 App
end

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!

New Call-to-action

 
Topics:Under the hood

Comments