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 One comment

Comments

  1. Avatar replica rolex said 1437 days later:
    $75 Replica Rolex Watches sale, Our site provides Rolex replica, replica Rolex Watches, replica breitling, replica Cartier, replica Omega, Tag Heuer Watches. . .more than 100 famous rolex brands" rolex air king rolex datejust rolex day date rolex daytona rolex gmt rolex submariner rolex yachtmaster a lange sohne watches alain silberstein watches bell ross watches breguet watches breitling watches bvlgari watches cartier watches omega watches patek philippe watches

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