Friday, February 03, 2006

Rails assertion logging

Robby Russell, who is working on a new book for O'Reilly press, posted a neat trick on logging from within your tests.

By adding this in addition to his logger method, I'm also able to log all the assertion messages to test.log when they fail - without any changes to my tests. I wouldn't usually care about logging in tests unless they fail, so that works even better for me.

#test_helper.rb:

class Test::Unit::TestCase

# Robby's method
def logger
RAILS_DEFAULT_LOGGER
end

end

# my addition
module Test
module Unit
module Assertions
alias_method :assert_block_original, :assert_block

def assert_block(message="assert_block failed.",
&block)
assert_block_original(message, &block)
rescue AssertionFailedError => error
logger.info(message.to_s)
raise error
end
end
end
end



I'm looking forward to Robby's book. Should be chock full of goodly nuggets. He's also presenting at Canada on Rails ("Sneaking Rails into the (Legacy) System"). As a guerilla Rubyist, I'm hoping for some new tricks from that too.