使用ruby抑制输出到控制台 [英] suppresing output to console with ruby

查看:341
本文介绍了使用ruby抑制输出到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些单元测试,如下所示:

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

,但是在断言之前运行以执行逻辑的方法会通过 puts 向控制台输出各种消息。



有没有一个快速,也许内置的方法来抑制输出到控制台?我只对该方法对模型对象的最终效果感兴趣,并且为了保持控制台基本清洁,我希望找到一种方法来简单地防止所有输出到控制台,而不重写或注释掉那些 puts 语句只是为了我的测试。



这绝对不是一个关键问题,

解决方案

我在测试中使用以下代码片段来捕获和测试STDOUT

p>

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



使用此方法,以上将变为:

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

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.

解决方案

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

这篇关于使用ruby抑制输出到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆