Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
Leonard Avatar asked Dec 31 '14 05:12

Leonard


1 Answers

The magic is to use capture_subprocess_io

 out, err = capture_subprocess_io do
     do_stuff
 end
like image 57
Leonard Avatar answered Sep 22 '22 12:09

Leonard