Space Vatican

Ramblings of a curious coder

Make Your Tests Run a Little Quicker for Free

It’s a good thing when tests run quickly. You get a shorter feedback cycle, you’re unlikely to move on to something else while your tests are running. Another good thing is ruby-debug: a fast debugger for ruby, worth its weight in gold when you need it. As of Rails 2.1 ruby-debug is always loaded and active during tests.

Having the debugger there does have some overhead. Not much, but it’s still there. You’re incurring that overhead whether your tests need it or not. On your CI server, it’s pure wasted time for example. Even running locally it’s frequently unecessary - most of the time when I run the tests I’m just running the tests, not using the debugger to try to understand a test failure.

So, without further ado I present this:

1
2
3
unless ENV['DEBUGGER']
  Debugger.stop if defined?(Debugger)
end

Stick it in your test_helper.rb, just below where it says

1
require 'test_help'

Run your tests again, and hey presto, faster! It does very from app to app, on some of the smaller apps I have the difference is pretty marginal, on the bigger apps I’ve got gains of up to 20-30%. I expect that on the smaller ones loading the Rails environment, setting up fixtures etc… dominates actual test runtime. And the day you do need to run the tests under the debugger it’s as easy as

1
rake DEBUGGER=true

if you’re using rake to run your tests or

1
DEBUGGER=true ruby -Itest test/unit/some_test.rb

if you’re running an individual test (this might change according to what shell you use). In fact most of the time you won’t even need to do this, as calling debugger calls Debugger.start for you.