在 RSpec 中捕获 STDOUT

5

我刚开始学习Ruby单元测试,但是在创建一个检查 STDOUT 的规范时遇到了一些问题。我知道如何测试 Class/Method 中的 STDOUT,但我想测试来自常规 Ruby 文件中不属于 Class/Method 的 puts 语句。

这里是来自 my_file.rb 的简单一行代码:

puts "Welcome to the Book Club!"

这里是规范说明: my_spec.rb
require_relative 'my_file.rb'

  describe "Something I'm Testing" do
    it 'should print Welcome to the Book Club!' do

        expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout

      end
    end

我收到了以下错误信息:
Failures:

  1) Something I'm Testing should print Welcome to the Book Club!
     Failure/Error: expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout

       expected block to output "Welcome to the Book Club!\n" to stdout, but output nothing
       Diff:
       @@ -1,2 +1 @@
       -Welcome to the Book Club!
       # ./spec/my_spec.rb:9:in `block (2 levels) in <top (required)>'

Finished in 0.01663 seconds (files took 0.08195 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/my_spec.rb:7 # Something I'm Testing should print Welcome to the Book Club!

我以为可以使用$stdout来捕获my_file.rb中的STDOUT,但这样无法正常工作。输出一直在说什么都没有。我找到了一篇文章,讲述了通过StringIO来捕获输出的方法Testing STDOUT output in Rspec
但是那种方法对我不起作用。我错在哪里了?
谢谢!
1个回答

8

当你在测试运行之前就在顶部引入了my_file.rb时,你的puts方法会被调用。请在测试代码内引入它。

describe "Something I'm Testing" do
  it 'should print Welcome to the Book Club!' do
     expect { require_relative 'my_file.rb' }.to output("Welcome to the Book Club!\n").to_stdout
  end
end

谢谢!像魔法一样顺利的工作。下次会记在心里。 - salce
1
如果@Uzbekjon回答了您的问题,请通过单击检查图标接受他的答案。有关更多信息,请参见http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。 - Keith Bennett
1
这个解决方案是有效的,但是如果您有多个具有不同stdout输出的测试,则第一个测试的输出会干扰第二个测试的输出。 - Sebastian Corneliu Vîrlan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接