How to Debug a Ruby on Rails Application

How to Debug a Ruby on Rails Application

This article I will show you how you can easily debug your Ruby on Rails application.

Setup
If you’re using the default Rails Rack server, Webrick – the best debugging tool I’ve been able to find out there is pry. First you need to add the pry gem to your Gemfile. Since this is used for development purposes. Open up your Gemfile file so that it looks sometings like:

Gemfile
1
2
3
group :development, :test do
  gem 'pry'
end

Then run bundle install to install it:

1
bundle install

Usage
Basically, Whenever one of your actions crashes and you can’t figure out straight away what caused it to crash. What you need to do is invoke binding.pry somewhere in your code, which will create a Pry session at the point it’s called. This will pretty much open a ‘developer console’ where you can play around with all the objects that have been defined up until you called binding.pry. Then you can then easily debug your action, like you’d regularly do in an irb console. When you’re done with the Pry session the program will resume.

Here’s how this would work in a regular create action from Users controller:

users_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
def create
  user = User.create(user_params)
  binding.pry # Start a pry session to see if the new user looks the way we want
  if user.save
     flash.now[:success] = "User saved successfully"
     sign_in user
     redirect_to user
  else
     flash.now[:error] = "Something went wrong: #{user.errors.full_messages}"
     render 'new'
  end
end

Well, after you run the create action – you should view the Pry session in the console, where your rails server is running.

So far so good, That’s it!!! See yar!!! :)