我刚开始学习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。但是那种方法对我不起作用。我错在哪里了?
谢谢!