All tests go green
July 18th, 2007
Many rails kiddies as well as pros alike have blogged something about colorizing your test results. However, few of the hacks seemed to work in Windows without requiring other gems or fiddlings. So here’s my simple solution which borrows heavily from Pat Eyler’s RedGreen gem. All it requires is to append the following snippet to the end of your test/test_helper.rb, and append COLORIZE after the rake command, like so:
$ > rake test:all_but_integration COLORIZE
And here’s the code to make your console look like your Mother’s Salad O’ Tomatoes and Lettuce:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
if ENV['COLORIZE'] require 'test/unit' require 'test/unit/ui/console/testrunner' module Color COLORS = { :clear => 0, :red => 31, :green => 32, :yellow => 33 } def self.method_missing(color_name, *args) colname = color_name.to_s ansi_color = (colname =~ /^light/ ? light_color(colname.gsub(/light/, '')) : color(colname)) ansi_color + args.first + color(:clear) end def self.color(color) "\e[#{COLORS[color.to_sym]}m" end def self.light_color(color) "\e[1;#{COLORS[color.to_sym]}m" end end class Test::Unit::UI::Console::TestRunner def adjust_io_if_required if !@io_set && PLATFORM =~ /win32/ require 'Win32/Console/ANSI' @io = Win32::Console::ANSI::IO.new @io_set = true end end def output_single(something, level=NORMAL) return unless (output?(level)) adjust_io_if_required something = case something when '.' then Color.lightgreen('.') when 'F' then Color.lightred("F") when 'E' then Color.lightyellow("E") else something end @io.write(something) @io.flush end end class Test::Unit::TestResult alias :orig_to_s :to_s def to_s if orig_to_s =~ /\d+ tests, \d+ assertions, (\d+) failures, (\d+) errors/ Color.send($1.to_i != 0 || $2.to_i != 0 ? :lightred : :lightgreen, $&) end end end class Test::Unit::Failure alias :old_long_display :long_display def long_display old_long_display.sub('Failure', Color.lightred('Failure')) end end class Test::Unit::Error alias :old_long_display :long_display def long_display old_long_display.sub('Error', Color.lightyellow('Error')) end end end |
Have fun.
1 Response to “All tests go green”
Sorry, comments are closed for this article.

July 19th, 2007 at 08:13
I turned it to Rails plugin, which is available from svn://majakari.net/rails/colorized_test (sorry, no http interface).