32

When testing a JSON response from an RSPEC controller test using DHH's JBuilder, my response.body is always "{}". It works fine in development/production modes AND when I use the to_json method instead of jbuilder, I get proper JSON in my response.body.

Anyone have a clue as to why my response.body would always be "{}" when testing?

----- Debugger

it "should return the cart items via JSON", :focus do

get :index, :format => :json
end

(rdb:1) response.body

"{}"

Kirk
  • 1,521
  • 14
  • 20

2 Answers2

68

For anyone that is having the same issue. I have figured it out.

You must call render_views within the controller tests you are doing. If you do that, you should then see a response.body with your JSON contained :)

freemanoid
  • 14,592
  • 6
  • 54
  • 77
Kirk
  • 1,521
  • 14
  • 20
  • You must call `render_views` because when running controllers, view rendering is by default disabled. This speeds up the running of the test since you should only be testing controller behavior in a controller test. – a moose Jul 24 '14 at 22:50
  • 2
    how to use `render_views`, ref: https://www.relishapp.com/rspec/rspec-rails/v/3-5/docs/controller-specs/render-views – Spark.Bao Sep 08 '16 at 07:34
  • https://github.com/rspec/rspec-rails > Note: To encourage more isolated testing, views are not rendered by default in controller specs. If you are verifying discrete view logic, use a view spec. If you are verifying the behaviour of a controller and view together, consider a request spec. You can use `render_views` if you must verify the rendered view contents within a controller spec, but this is not recommended. – Spark.Bao Sep 09 '16 at 08:49
27

You could find a solution from https://github.com/rails/jbuilder/issues/32

So in rspec/spec_helper.rb

RSpec.configure do |config|
  # https://github.com/rails/jbuilder/issues/32
  config.render_views = true
end

After above option are added, JSON result will show via jbuilder renderer

neocoin
  • 341
  • 4
  • 8
  • 1
    You can't put this in the `spec_helper.rb` anymore. Now you have to do this on the `rails_helper.rb` more info: https://github.com/rspec/rspec-rails/issues/1918 (I commented because edit queue is full) – Lucas Emerick Feb 28 '21 at 16:49