Ruby Debug

May 4th, 2008

With the gem ruby-debug, you can get your code to jump into a debugger. In the debugger you can examine and manipulate your code similar to how you would in the interactive ruby console.


gem instal ruby-debug

Calling the debugger

One way to get your code to call the debugger is with the keyword debugger.

One case where I found this useful was when an rspec was failing unexpectedly.

NOTE: debugger require's rubygems and ruby-debug. In the following code I have added the require's on the same line as the call to debugger, because I will delete the whole line once I've found the problem. This is because I don't want unnecessary code lying around in my tests

1
2
3
4
5
6
7
it "should find note, given id" do
      note_id = 1
      do_get note_id
      Note.should_receive(:find).with(note_id).and_return(mock_note)
      get :edit 1
      require "rubygems"; require "ruby-debug"; debugger      
    end

When it hit the debugger line a prompt came up. I used it to print the value of note_id and params[:id], and saw the reason it failed was due to the compared values being of different types.

1
2
3
4
(rdb:1) p note_id
1
(rdb:1) p params[:id]
"1"

Making the debugger behave more like the console

If you want to set a value in the console, by default you can't do


myobj.name = tim
you have to use eval

eval myobj.name = tim
however if you type

set autoeval

you no longer need to use eval keyword.


Also, if you don't want to have to use the function p (print) to display an objects value you can set the autolist option


set autolist

Debug Configuration File

You can preload options into the debugger, by creating the file .rdebugrc in your home directory and adding them there

1
2
3
4
set autolist
set autoeval
set autoreload
set forcestep

Tip from: Ruby-debug quick tips: init file and -n option

Ruby Debug screencast

I found the screencast Ruby Debug Basics really useful.

Leave a Reply