Rails test jbuilder json response with rspec
Testing jbuilder response in rspec integration tests requires an extra helper method to be included in test. Requests in integration tests do not render json response unless we include render_views helper.
Today, while working on
rspec controller tests
for
jbuilder responses in Rails application,
the response for get
or post
requests was being returned as an empty string.
The setup for the rspec test was as given below. Let’s say we are showing post in json format using jbuilder.
Controller
JBuilder rendering json
View rendering json for the @posts
initialized in controller.
This will render json response as given below.
Rspec Test
As we can see, this test tries to get json response for the show action on posts controller.
If we inspect the repsonse, it is as given below.
This means jbuilder json response was not returned by the show
action
on
the posts_controller
.
render_views in tests
To be able to render json response from jbuilder view file, we need to add render_views.
Working rspec test with Jbuilder json
Now, the example can be written as given below.
And running above rspec test will give the expected json response.
References
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox