检查 RSpec 中是否存在“puts”(缺少)
我在 ruby 项目中使用 rspec 进行测试,并且我想指定当使用 -q 选项时我的程序不应输出任何内容。我尝试过:
Kernel.should_not_receive :puts
当控制台有输出时,这并没有导致测试失败。
如何验证文本输出是否缺失?
I am using rspec for my test in a ruby project, and I want to spec that my program should not output anything when the -q option is used. I tried:
Kernel.should_not_receive :puts
That did not result in a failed test when there was output to the console.
How do I verify the absents of text output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
puts 在内部使用 $stdout 。由于它的工作方式,最简单的检查方法就是使用:
$stdout.should_not_receive(:write)
它检查没有按预期写入 stdout。
Kernel.puts(如上所述)只会导致测试失败
被明确地这样调用(例如 Kernel.puts“Some text”),其中
大多数情况下,它是在当前对象的范围内调用的。
puts uses $stdout internally. Due to the way it works, the easiest way to check is to simply use:
$stdout.should_not_receive(:write)
Which checks nothing is written to stdout as expected.
Kernel.puts (as above) would only result in a failed test when it
is explictely called as such (e.g. Kernel.puts "Some text"), where
as most cases it's call in the scope of the current object.
上面接受的答案是不正确的。它“有效”是因为它没有收到 :write 消息,但它可能收到了 :puts 消息。
正确的行应为:
此外,您还需要确保将该行放在将写入 STDIO 的代码之前。例如:
这是一个项目中实际工作的 RSpec
The accepted answer above is incorrect. It "works" because it doesn't receive a :write message but it might have received a :puts message.
The correct line should read:
Also you need to make sure you put the line before the code that will write to STDIO. For instance:
That's an actual working RSpec from a project