How can I change ruby log level in unit tests based on context

Posted by Stuart on Stack Overflow See other posts from Stack Overflow or by Stuart
Published on 2010-05-24T15:35:09Z Indexed on 2010/05/27 13:31 UTC
Read the original article Hit count: 183

Filed under:
|

I'm new to ruby so forgive me if this is simple or I get some terminology wrong.

I've got a bunch of unit tests (actually they're integration tests for another project, but they use ruby test/unit) and they all include from a module that sets up an instance variable for the log object. When I run the individual tests I'd like log.level to be debug, but when I run a suite I'd like log.level to be error. Is it possible to do this with the approach I'm taking, or does the code need to be restructured?

Here's a small example of what I have so far.

The logging module:

#!/usr/bin/env ruby

require 'logger'

module MyLog

  def setup
    @log = Logger.new(STDOUT)
    @log.level = Logger::DEBUG
  end
end

A test:

#!/usr/bin/env ruby

require 'test/unit'
require 'mylog'

class Test1 < Test::Unit::TestCase

  include MyLog

  def test_something
    @log.info("About to test something")
    # Test goes here
    @log.info("Done testing something")
  end
end

A test suite made up of all the tests in its directory:

#!/usr/bin/env ruby

Dir.foreach(".") do |path|
  if /it-.*\.rb/.match(File.basename(path))
    require path
  end
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about unit-testing