Ruben Laguna's blog

Aug 17, 2011 - 1 minute read - Comments

Running a custom TestRunner from rake

I was surprised when I searched in Google for ways of running a custom TestRunner in a Rake::TestTask and I couldn’t find anything directly.

So after figuring out myself how it’s done I decided to share it here:

Let’s say that you have the following TestRunner (learn how to write your custom TestRunner)

#  Usage:
#  ruby -rstat_runner [test] --runner=stat
#  http://endofline.wordpress.com/2008/02/11/a-custom-testrunner-to-scratch-an-itch/require 'test/unit'
require 'test/unit/ui/console/testrunner'
class StatRunner < Test::Unit::UI::Console::TestRunner
def finished(elapsed_time)
nl
output("="*72)
output("|"*"Finished in #{elapsed_time} seconds.".center(70)*"|")
output("="*72)
nl
output(@result)
end
end

Test::Unit::AutoRunner::RUNNERS[:stat] = proc do |r|
StatRunner
end

This new StatRunner is very simple and the only customization is that it prints the result line wrapped in a box.

Now imagine that this StatRunner is defined in the test/stat_runner.rb file. The rake task in the rakefile would look like:

# http://rake.rubyforge.org/classes/Rake/TestTask.html
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test' # test dir is in, so we can do -rstat_runner
test.ruby_opts=['-rstat_runner'] # require stat_runner.rb in spawned ruby process
test.pattern = 'test/****/test_*.rb'
test.verbose = true
test.options="--runner=stat" #force to use the new runner called stat (has to be in RUNNERS)
end

That’s it. Now if you run your rakefile you’ll get

  Started

  ========================================================================
  |                    Finished in 0.000103 seconds.                     |
  ========================================================================

  1 tests, 1 assertions, 0 failures, 0 errors

Compiling OpenChronos in Windows Sublime Text 2 RVM and RSpec