Debugging ruby-on-rails application with pry

suggest change

pry can debug a Ruby application. Adding it to a Rails app is straightforward.

Setup

To debug with pry:

group :development, :test do
  gem 'pry'
end

Use

Put binding.pry where execution should stop. That works in any file Ruby runs: controllers, models, and views.

  1. Debugging a Controller

app/controllers/users_controller.rb

class UsersController < ApplicationController
  def show
    user_id = params[:id]
    # Stop here to inspect the params for this action.
    binding.pry
    @user = User.find(user_id)
    respond_to do |format|
      format.html
    end
  end
end

The server stops in a pry console when a request hits UsersController#show. From there you can inspect params and query User.

  1. Debugging a View

app/views/users/show.html.haml

%table
  %tbody
    %tr
      %td ID
      %td= @user.id
    %tr
      %td email
      %td= @user.email
    %tr
      %td logged in ?          
      %td
        - binding.pry
        - if @user.logged_in?
          %p= "Logged in"
        - else
          %p= "Logged out"

The server stops in pry while rendering users/show, before the response is sent. Use that stop to check @user.logged_in?.

  1. Debugging a Model
# app/models/user.rb
class User < ActiveRecord::Base
  def full_name
    binding.pry
    "#{first_name} #{last_name}"
  end
end

This stop runs whenever full_name is called. Pry is enough for breakpoints in controllers, views, and models. binding.pry will also stop a production process, so keep the gem out of the production group.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents