Debug Ruby code

Updated . Posted . Visible to the public.

This is an awesome gadget in your toolbox, even if your test coverage is great.

  • gem install ruby-debug (Ruby 1.8) or gem install debugger (Ruby 1.9)
  • Start your server with script/server --debugger
  • Set a breakpoint by invoking debugger anywhere in your code
  • Open your application in the browser and run the code path that crosses the breakpoint
  • Once you reach the breakpoint, the page loading will seem to "hang".
  • Switch to the shell you started the server with. That shell will be running an irb session where you can step through the code, inspect context and watch variables by typing commands.

Commands available on the debug shell (with short commands)

Run until program ends, hits a breakpoint or reaches line nnn

continue (c) – you may pass a line number

Step over the current line

next (n)

Step into the current line

step (s)

Step out

finish (f)

Print caller stack

backtrace (bt)

Go one level up in the caller stack without moving the debugger

up (u)

Go one level down in the caller stack without moving the debugger

down

Add a new breakpoint from an existing debugger session

break <filename>:<line> \
For example: break app/models/user.rb:42 (path names can be relative and absolute)

Notepad – its content will be displayed when the program stops

display <expression> – add to list \
display – print expression list

Reload source code

reload (r)

Get context information

info (i)

Help

help (h) – pass a command for specific help

To some commands you may pass a number, e.g. up 3 will take you 3 levels higher in the caller stack.

Debugging in RubyMine

Debugging in RubyMine is even easier:

  • To set a breakpoint, click on an area left to the code.
  • There is an icon that runs the server in debug mode.
  • You can now step through the code with buttons.
  • Unfortunately you cannot execute arbitrary code in irb while debugging in RubyMine. Debug without Rubymine if you need to do so.

Debugging in your tests

When you run RSpec or Cucumber, Ruby is already in debug mode. Tests will open a debugging shell when they cross a breakpoint set with debugger.

To debug a Cucumber feature, use this step definition:

Then /^debugger$/ do
  debugger
end

Make the Ruby debugger work in Bundler projects

Bundle the ruby-debug gem into the :development, :test and :cucumber groups.

Problems?

If you cannot access local variables etc, see this card.

Henning Koch
Last edit
Besprechungs-PC
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-09-08 18:51)