rubytestingconsolesuppress-warnings

suppresing output to console with ruby


I am writing some unit tests like the following:

def executing_a_signal
  a_method(a_signal.new, a_model, a_helper);
  assert_equal(new_state, a_model.state)
end

The tests work fine, but the method which runs just before the assertion to execute the logic prints various messages to the console, mainly via puts.

Is there a quick, perhaps built-in, way to suppress that output to the console? I am only interested in the final effect of the method on the model object, and for the sake of keeping the console clean basically, I was hoping to find a way to simply prevent all output to the console without re-writing or commenting out those puts statements just for my tests.

It is definitely not a critical issue, but would very much like to hear any thoughts or ideas (or workaround) on it.


Solution

  • I use the following snippet in tests to capture and test STDOUT

    def capture_stdout(&block)
      original_stdout = $stdout
      $stdout = fake = StringIO.new
      begin
        yield
      ensure
        $stdout = original_stdout
      end
      fake.string
    end
    

    With this method, the above would become:

    def executing_a_signal
      capture_stdout { a_method(a_signal.new, a_model, a_helper) }
      assert_equal(new_state, a_model.state)
    end