1

Rails 3.0.10, Ruby 1.9.2, ActiveSupport::TestCase

I would like to print to STDOUT the log portion of tests that fail (only). If there is a plugin for that that I didn't find, please be so kind to tell me. Otherwise, I would like to know:

  • How do I get the result (pass, fail, error) in teardown? In a similar question it is suggested to overwrite all assert methods to rescue exceptions, but I don't like that approach too much.

My approach would be to have a setup that changes logging to a string and have the string pumped to STDOUT on a fail.

4

1 に答える 1

2

These methods all work fine in a teardown method:

self.passed?
self.class.name
self.method_name

So in setup, you can save your old logger and create a new one that logs to a string buffer:

@old_logger = Rails.logger
@old_ar_logger = ActiveRecord::Base.logger
@current_buffer = StringIO.new
Rails.logger = Logger.new(@current_buffer)
ActiveRecord::Base.logger = Rails.logger

And in teardown, reset loggers, test for passed? and dump buffered log in case it did not:

Rails.logger = @old_logger
ActiveRecord::Base.logger = @old_ar_logger
unless self.passed?
  @current_buffer.close_write
  STDOUT << @current_buffer.string
  @current_buffer.close
end

It works fine for me. Just beware that if you have an endless loop or something similar, you will not notice that easy.

于 2011-12-07T10:58:46.453 に答える