Debugging Specs

It is easy enough to debug specs on by one. For this you just run the ruby file that contains the spec with ruby-debug instead of ruby:

rdebug spec/rur_spec.rb

But when running via rake, you can’t do this. A simple solution is to add these lines in the spec file you want to debug (or in spec_helper.rb):

require_library_or_gem 'ruby-debug'
Debugger.start

And you are in business…

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

I use ruby-debug quite a bit (too much? perhaps). And every time I start it, I find myself setting a few options (always the same ones), and it finally got to the point where I thought there had to be a better way. And there was! (Thank you, Kent)

The solution is even documented in some recent release notes:

Create a .rdebugrc in your home directory (it also looks for one in the current directory first):

set autolist
set autoeval
set autoreload
set forcestep

And voila! Each time you start rdebug, it executes this script.

An other good tip: run with -n to avoid stopping on the first instruction, now that you don’t need to run all these commands.

Update: with version 0.10, -n does not seem to be recognized, but —no-stop still works.

RadRails is switching to Ruby-debug

According to Kyle, one of the tireless developer of Rad Rails, he is working on incorporating ruby-debug.

For more details about ruby-debug, see my write up about it.

The command line is great, and there are times when you are working on a remote server where nothing else will do. But having the ability to set breakpoints at the click of the mouse, see your variables in a separate pane, see a lot more of your source code is something quite convenient.

And with the added speed of ruby-debug, this should make debugging in Rad Rails something you can’t afford not to use.

This is very welcome news and I look forward to use it!

A better Rails debugger: ruby-debug

Just a few days ago, Kent Sibilev quietly released an amazing little plugin with far reaching consequences: ruby-debug. This is a marked improvement over Ruby’s own rdebug. The major difference is that he removed the major slow down that impacted rdebug usability with Ruby on Rails so it is blazing fast.

Instead of using the Kernel#set_trace_func API, which makes it possible to implement a debugger in Ruby, but has a negative effect on the speed on your program execution, he uses a native extension with a new hook using the Ruby C API

For each trace call Ruby interpreter creates a Binding object, even though it is not being used most of the time. ruby-debug library moves most of the functionality of debug.rb to a native extension, this way significantly improving the execution of your program.

This means that watchpoints and the standard tracing facility are not supported, but I’m gladly giving that up for the comfort and speed. And if you are wondering how the speed is, that is really the difference between utter frustration each time you debug something to bliss!

Previously I covered some options for Debugging in Rails. This is going to become my preferred option by far, and I’m willing to bet this will become yours too. Why? Because you can see the source code of where you are, you can execute step while watching some or your variables, you can inspect of your variables (this you could do with breakpointer), you can use conditional breakpoints, you can get a list of expressions to be displayed every time you step. The downside compared to breakpointer? You can’t do it remotely, which in most instances, as best as I can tell, is not going to be a problem at all.

Installation

Ruby-debug comes as a gem so to install, just run:

sudo gem install ruby-debug

Make sure you chose the proper windows or ruby version depending on your platform.

Using ruby-debug

To use in your rails application, assuming you want this to only be available in development mode (this is not such a great idea to leave in in production mode, just in case you forget to remove the breakpoints, and also for performance reasons as I’ll explain in a bit)

In environement.rb add the following:

SCRIPT_LINES__ = {} if ENV['RAILS_ENV'] == 'development'

This line is important if you want to be able to see your source code. SCRIPT_LINES__ is an obscure feature of the ruby interpreter. If it is defined, it will store all loaded ruby file in a hash, which debug-ruby will use to display where you are in your source code. The only problem is that it can have some impact on performance, and worst of all, use up quite a bit of memory, which is not so good in production (hence the “if ENV[‘RAILS_ENV’] == ‘development'”). SCRIPT_LINES__ needs to be initialized as early as possible so it can capture all loaded ruby files.

To add a breakpoint, you will need to use:

require 'ruby-debug'
...
def your_method
  ...
  debugger if ENV['RAILS_ENV] == 'development'
  ...
end

Then start your app using webrick (it does not work with lighttpd and I have not investigated why just yet):

script/server webrick

When the code hits the breakpoint, you are in a console like mode (not unlike irb or script/console).

Ruby-debug commands

  • b[reak]

    list breakpoints
  • b[reak] [file|class:]LINE|METHOD [if expr]
  • b[reak] [class.]LINE|METHOD [if expr]

    set breakpoint to some position, optionally if expr == true
  • cat[ch]

    show catchpoint
  • cat[ch] EXCEPTION

    set catchpoint to an exception
  • disp[lay] EXPRESSION
    add expression into display expression list
  • undisp[lay][ nnn]

    delete one particular or all display expressions if no expression number given
  • del[ete][ nnn]

    delete some or all breakpoints (get the number using “break”)
  • c[ont]

    run until program ends or hit breakpoint
  • r[un]

    alias for cont
  • s[tep][ nnn]

    step (into methods) one line or till line nnn
  • n[ext][ nnn]

    go over one line or till line nnn
  • w[here]

    displays stack
  • f[rame]

    alias for where
  • l[ist][ (-|nn-mm)]

    list program, – list backwards, nn-mm list given lines. No arguments keeps listing
  • up[ nn]

    move to higher frame
  • down[ nn]

    move to lower frame
  • fin[ish]

    return to outer frame
  • q[uit]

    exit from debugger
  • v[ar] g[lobal]

    show global variables
  • v[ar] l[ocal]

    show local variables
  • v[ar] i[nstance] OBJECT

    show instance variables of object
  • v[ar] c[onst] OBJECT

    show constants of object
  • m[ethod] i[nstance] OBJECT

    show methods of object
  • m[ethod] CLASS|MODULE

    show instance methods of class or module
  • th[read] l[ist]

    list all threads
  • th[read] c[ur[rent]]

    show current thread
  • th[read] [sw[itch]] nnn

    switch thread context to nnn
  • th[read] stop nnn

    stop thread nnn
  • th[read] resume nnn

    resume thread nnn
  • p EXPRESSION

    evaluate expression and print its value
  • pp EXPRESSSION

    evaluate expression and print its value
  • h[elp]

    print this help
  • RETURN KEY

    redo previous command. Convenient when using list, step, next, up, down,
  • EVERYHTING ELSE

    evaluate

Happy debugging!

Javascript console

Javascript is great when it works. When it doesn’t work, it can get you from happy to miserable in less time than it takes you to say XmlHttpRequest.

Today I just found (via Ajaxian) an interesting tool that I’m adding to my arsenal when it comes to figuring out what’s happening in javascript. Definitely an invaluable debugging tool. It is called JavaScript Shell. When you embed the script, you get a command line window where you can make javascript calls directly from inside your web page.

You can call any method, inspect objects (using props), see where DOM objects are (using blink), and the killer feature, in my view, is the autocompletion using the tab key! It also features a command history, which is very convenient to try variations of the same call.

And if that wasn’t enough, you can also use the script as a bookmarklet. There is a Firefox version, and an Internet Explorer version available from Curiosity is bliss (ported to IE by Julien Couvreur).

You should try the script for yourself.

This is a great tool to debug, or even try a few things quickly and this will be a good complement to the rails console. It sure beats having to reload the page!

readable output in rails script/breakpointer

After hours spent in breakpointer struggling to make sense of the output, I figured there had to be a better way to look at a stack trace than what the default output provides:

irb(ArticlesController):007:0> caller
=> [“./vendor/rails/railties/lib/breakpoint.rb:512:in `breakpoint’”, “./vendor/rails/railties/lib/breakpoint.rb:512:in `breakpoint’”, “./vendor/rails/actionpack/lib/action_controller/caching.rb:510:in `cache_sweeper’”, “./app/controllers/articles_controller.rb:7”, …]

Well, after some research, I found at least 4! And they work for any data structure, not just for stack traces, but I’m a pretty happy camper just with cleaner stack traces!

Solution #1

Building on Using the standard output in breakpointer, you can use each to get a more decent output.

caller.each { |x|  client.puts x }

which returns:

./vendor/rails/railties/lib/breakpoint.rb:512:in `breakpoint’
./vendor/rails/railties/lib/breakpoint.rb:512:in `breakpoint’
./vendor/rails/actionpack/lib/action_controller/caching.rb:510:in `cache_sweeper’
…

Solution #2

Use PrettyPrint

client.require ‘pp’
client.pp caller

Solution #3

Use YAML

client.require ‘yaml’
client.y caller

Solution #4

Use to_yaml

client.puts caller.to_yaml

These methods can also be used to display any complex data.

Try it on the request object for example.

To avoid having to type the require each time, add to .irbrc:

require ‘yaml’
require ‘pp’

Using the standard output in script/breakpointer

When you use script/breakpointer, once you have stopped in irb, if you try using print, puts or some other way to display something, your ouput goes to your main rails output, not to irb, which is not quite convenient.

First, it took me a while to realize where the output was in fact going. I guessed I was not too quick on that one.

Second, even knowing where to look, I did not find this solution very satisfying.

It turns out there is a solution. the client variable can help you use the right output

client.print “hello\n”

will output:

hello
=> nil

Works the same for puts.

Running your rails app without a browser

I still get to switch over to rails 1.1. Mind you, I have been running around with my hair on fire doing more mundane things like preparing my tax return.

In building upon that article on integration testing by Jamis, I ran accross an article from Mike Clark is describing in great details how to run your Rails App, without a browser.

And this is just what the doctor ordered for fairly complex test scenarii. Just imagine the possibility of automating full scripts that go across multiple controllers, exercise how your models related to each other…

Plus that app object has got to be useful while debugging!

Debugging in Rails

In my own experience, here’s what a good debugger needs:

  1. breakpoints (with conditions even better)
  2. stepping
  3. object list (locals, globals, objects)
  4. watches
  5. resetting the current instructions
  6. modify objects

4, 5 or 6 are really icing on the cake, but help separate the men from the boys. Although these can help save a tremendous amount of time, especially when a certain situation is really hard to reproduce because you get several shot at reproducing and fixing the problem in real time.

Best examples I have used (and abused): Steve Jasick’s “The Debugger”, and yes, Visual C++ (before the .net and C# days). Eclipse and the java debugger is not too bad either.

So why is this such an unpopular subject with such a limited support with Ruby and with Rails? Enquiring mind wants to know!

Best usable option in practice: breakpoint.

It meets requirements 1 through 3. Hey, you can even do conditional breakpoints!

Just insert a “breakpoint” call where you want to stop, and then run you app normally.

While you do that, run script/breakpointer to catch the breakpoint (assumes you are on the same machine).

There, you can check out any ruby expression like you can do in irb.

Some useful commands to help find out what’s there:

  • local_variables (list of all your local variables (whether initialized yet or no)
  • instance_variables (same as self, without the values)
  • caller (shows the stack trace, not terribly readable but the information is there)
  • methods (list all the method of the class you stopped in)

Just need to tough it up and get on with it till someone comes up with a better alternative. This brings back some fond memories of long ago when command line debuggers where all the rage, and all you had too. But I’m starting to date myself here so I’ll just shut up and set a few breakpoints to relax.

A word to the wise: do me a favor, and remove your breakpoints before deploying on your production environment. This could save you from ridicule. Not that this ever happened to me, right!

I’m very hopeful that the guys are RadRails will find a solution to get it to work faster and more reliably.

Installing readline on Kubuntu

Running script/console provides the delightful answer:

/usr/local/lib/ruby/1.8/irb/completion.rb:10:in `require’:
no such file to load – readline (LoadError)

Turns out that Kubuntu doesn’t have the curses libraries.

Here’s the begining of a solution

apt-get install libncurses5-dev libreadline5-dev (Ubuntu/Debian)

Then recompile the readline extension and go from there.

cd ext/readline
ruby extconf.rb
make
sudo make install

Read more