Logging in tests in Rails
To use the logger in tests in Rails is fairly simple, you can access the logger with RAILS_DEFAULT_LOGGER. However, the test.log file gets a little hard to read since you don’t know which test method generated the messages. This is a problem even if you don’t use the logger manually if you for example want to look at the SQL statements.
The following snippet generates a log message when each test method is called and one message when the test method is done. To use it you need to include the snippet in test_helper.rb and add log_test_methods in the end of your test class (I couldn’t figure out a better way to solve it).
class Test::Unit::TestCase
def self.log_test_methods
class_eval do
test_methods = instance_methods.select {|m| m.match(/^test/)}
test_methods.each do |method|
alias_method "orig_#{method}", method
define_method method do
begin
RAILS_DEFAULT_LOGGER.info ">>> #{method}"
send "orig_#{method}"
RAILS_DEFAULT_LOGGER.info "<<< #{method}"
rescue => e
RAILS_DEFAULT_LOGGER.info "<<< #{method}"
raise e
end
end
end
end
end
end
Zero comments