Ruben Laguna’s blog

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<span class='line'># Usage:
</span><span class='line'>#   ruby -rstat_runner [test] --runner=stat
</span><span class='line'># http://endofline.wordpress.com/2008/02/11/a-custom-testrunner-to-scratch-an-itch/require 'test/unit'
</span><span class='line'>require 'test/unit/ui/console/testrunner'
</span><span class='line'>class StatRunner &lt; Test::Unit::UI::Console::TestRunner
</span><span class='line'>  def finished(elapsed_time)
</span><span class='line'>    nl
</span><span class='line'>    output("="*72)
</span><span class='line'>    output("|"+"Finished in #{elapsed_time} seconds.".center(70)+"|")
</span><span class='line'>    output("="*72)
</span><span class='line'>    nl
</span><span class='line'>    output(@result)
</span><span class='line'>  end
</span><span class='line'>end
</span><span class='line'>
</span><span class='line'>Test::Unit::AutoRunner::RUNNERS[:stat] = proc do |r|
</span><span class='line'>  StatRunner
</span><span class='line'>end</span>

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:

1
2
3
4
5
6
7
8
9

1
2
3
4
5
6
7
8
9
<span class='line'># http://rake.rubyforge.org/classes/Rake/TestTask.html
</span><span class='line'>require 'rake/testtask'
</span><span class='line'>Rake::TestTask.new(:test) do |test|
</span><span class='line'>  test.libs &lt;&lt; 'lib' &lt;&lt; 'test'  # test dir is in, so we can do -rstat_runner
</span><span class='line'>  test.ruby_opts=['-rstat_runner'] # require stat_runner.rb in spawned ruby process  
</span><span class='line'>  test.pattern = 'test/**/test_*.rb'
</span><span class='line'>  test.verbose = true
</span><span class='line'>  test.options="--runner=stat" #force to use the new runner called stat (has to be in RUNNERS)
</span><span class='line'>end</span>

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

Comments

Copyright © 2015 - Ruben Laguna - Powered by Octopress