Debugging exceptions Rails 5 jbuilder views
There comes a time where regardless of your unit testing you have errors in production. But, alas, the exception isn't in your controller itself but the view!
There has been a quick and dirty way of getting the full stack trace in console for a while but it fails to hit the mark in Rails 4 and Rails 5.
Below is the full copy/paste snippet that will let you try and render a view in console. Very helpful with JSON APIs that use jbuilder that can have complex logic and multiple partial inheritance. Any error or exception will generate a full stack trace for you to debug with.
def rendered_view(view_path, variables = {})
view = ActionView::Base.new(Rails.configuration.paths['app/views'], variables)
view.extend ApplicationHelper
view.class_eval do
include Rails.application.routes.url_helpers
include ApplicationHelper
def protect_against_forgery?
false
end
end
view.render(file: view_path)
end
Example
Given a view like below
# views/api/users/show.json.jbuilder
json.foo foo
json.user @user.id
Use the helper method you'd use in production console like so to get the exception stack trace:
rendered_view('api/users/show', { 'user' => User.find(123), 'foo' => 'bar' })
# => ActionView::Template::Error: some exception you're debugging for
# from ...
# from ...
# ...
Or once you've resolved the error:
# => "{\"foo\":\"bar\":,\"user\":123}"
Happy hunting!
This posts's header is by Matthew Potter. Used under CC BY 2.0 license.