RSpec Controller Testing with JBuilder
I recently decided to use Jbuilder for an app we are working on to help people manage their watch later video queues. While Rails has some out of the box functionality for creating JSON APIs (like respond_to and respond_with), it can get out of hand when you try to customize the JSON you want to return from your controllers like ignoring some columns or customizing the way it looks.
As is usually the case in the Ruby on Rails world, a lot of smart people have created great gems to help address this issue. One of the more popular gems for example is RABL which is described in more detail in various articles.
While I have experimented with RABL for some other projects, I decided to use Jbuilder since I read some good reviews about it and also with the hope that it would provide better integration as it is built by the Rails Core Team.
So I installed it, wrote some tests and then proceeded to create the views. And this is when I started to run into some issues. While I was able to get the proper response when testing the API in the browser with a tool like Postman, my RSpec controller tests like the one below kept failing returning a null body:
json = JSON.parse(response.body) expect(json['token_type']).to eq 'bearer'
After a few frustrating hours, I finally found the solution to the problem (as always thank you Stack Exchange), which is to include render_views on top of the controller test file or to add the following block to your
# https://github.com/rails/jbuilder/issues/32 file:RSpec.configure do |config| config.render_views = true end