Jon Leighton

How to prevent Ruby's test/unit library from autorunning your tests

Today I had a situation where I wanted to use perftools.rb to profile a test suite, which was written with Ruby’s test/unit library.

test/unit installs an at_exit hook which runs all the tests before Ruby exits. This was problematic, because it meant that all the tests ran after perftools had already finished its profile.

So I wanted to turn off the autorunning and explicitly run the test suite. I found out how to monkey-patch test/unit to achieve this, and figured it might be useful to someone in the future, so:

Ruby 1.9

require 'test/unit'

class Test::Unit::Runner
  @@stop_auto_run = true
end

class FooTest < Test::Unit::TestCase
  def test_foo
    assert true
  end
end

Test::Unit::Runner.new.run(ARGV)

Ruby 1.8

require 'test/unit'

module Test::Unit
  def self.run?; true; end
end

class FooTest < Test::Unit::TestCase
  def test_foo
    assert true
  end
end

Test::Unit::AutoRunner.run

19 February 2012

Jon Leighton is an experienced software engineer, specialising in Ruby. He is based in the beautiful mountains of Snowdonia in North Wales, and is particularly interested in projects with a social purpose. Do get in touch if you'd like to chat.

Comments