Logging in tests in Rails

posted Sun, 11 Dec 2005 00:38:00 GMT by Jonas Bengtsson

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

Comments Zero comments

Comments

Respond

This is where you come in. Please leave a comment whether you agree, disagree or none of the above.

(required)

(to your blog or homepage)

(won't be shown nor shared)


  Preview