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
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
With json_spec, you have access to some great matchers like
have_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!