Sal*_*dec 2 ruby unit-testing rspec
我是Ruby的单元测试的新手,我在创建一个检查STDOUT的规范时遇到了一些麻烦.我知道如果我正在测试的代码是在类/方法中,如何测试STDOUT,但我想测试puts来自不在Class或Method中的常规Ruby文件的语句.
这是一个简单的一个班轮 my_file.rb
puts "Welcome to the Book Club!"
Run Code Online (Sandbox Code Playgroud)
这是规格
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
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
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!
Run Code Online (Sandbox Code Playgroud)
我以为我可以$stdout用来捕获STDOUT,my_file.rb但是没有用.输出一直没有说.我发现这篇文章讲述了通过Rspec中的测试STDOUT输出捕获输出StringIO
但这种方法对我不起作用.我究竟做错了什么?
谢谢!
在测试运行之前puts将my_file.rb权限包含在顶部时,将调用您的方法.将其包含在您的测试中.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2459 次 |
| 最近记录: |