rubyloggingminitest

Capture Ruby Logger output for testing


I have a ruby class like this:

require 'logger'
class T
  def do_something
    log = Logger.new(STDERR)
    log.info("Here is an info message")
  end
end

And a test script line this:

#!/usr/bin/env ruby

gem "minitest"
require 'minitest/autorun'

require_relative 't'

class TestMailProcessorClasses < Minitest::Test
  def test_it
    me = T.new

    out, err = capture_io do
      me.do_something
    end

    puts "Out is '#{out}'"
    puts "err is '#{err}'"
  end
end

When I run this test, both out and err are empty strings. I see the message printed on stderr (on the terminal). Is there a way to make Logger and capture_io to play nicely together?

I'm in a straight Ruby environment, not Ruby on Rails.


Solution

  • The magic is to use capture_subprocess_io

     out, err = capture_subprocess_io do
         do_stuff
     end