THE BITESITE BLOG
Rspecrabljsonresponses

Failing RSpec Tests when using RABL for JSON Responses

coding software ruby on rails rspec rabl

After about 5 years of doing Ruby on Rails development, there is one aspect that for the longest time never seemed to sit well with me: TDD. It wasn't that I didn't understand the benefits, and it wasn't that I didn't believe in it, but unlike many things Rails, there wasn't enough concrete motivation to do it. Over the past few months I finally started to get into it and I'll write all about my experiences in another post, but for now, I wanted to let you guys know about a specific problem I was having with TDD'ing an API I built.

I was building an API for a app using Ruby on Rails and following the http://apionrails.icalialabs.com/.

To render my JSON responses, I almost always use RABL now. I tried activemodelserializers when I was experimenting with Ember, but I quickly switched back to RABL.

Anyway, I was writing my tests I was having issues testing my JSON response. My typically test would look something like this:

it "renders a response" do create(:route) get :index, format: :json response_object = JSON.parse(response.body) expect(response_object.size).to eq(1) end

The issue is that no matter what I did, it seemed that my tests would fail. Upon further inspection, it looked like the response.body was empty. I was getting really frustrated so what I did was I abandoned my TDD and just tried it in the browser (well, more accurately in Postman). To my surprise, it was working.

So why were my tests failing and why was the response.body empty?

It all has to do with the fact that I was using RABL for the JSON responses. Because RABL uses Rails view rendering and by default Controller specs don't render views - the response.body was empty.

So the solution was as simple as adding

render_views

to the top of my specs so I had the followiing:

require 'spec_helper' describe Api::V1::MyController, type: :controller do render_views ... end

Alright, that's it for now. Hopefully this helps some peeps.

Caseyli
Casey Li
CEO & Founder, BiteSite