检查 RSpec 中是否存在“puts”(缺少)

发布于 2024-08-08 04:37:31 字数 177 浏览 3 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她如夕阳 2024-08-15 04:37:31

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.

困倦 2024-08-15 04:37:31

上面接受的答案是不正确的。它“有效”是因为它没有收到 :write 消息,但它可能收到了 :puts 消息。

正确的行应为:

$stdout.should_not_receive(:puts)

此外,您还需要确保将该行放在将写入 STDIO 的代码之前。例如:

it "should print a copyright message" do
  $stdout.should_receive(:puts).with(/copyright/i)
  app = ApplicationController.new(%w[project_name])
end


it "should not print an error message" do
  $stdout.should_not_receive(:puts).with(/error/i)
  app = ApplicationController.new(%w[project_name])
end

这是一个项目中实际工作的 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:

$stdout.should_not_receive(:puts)

Also you need to make sure you put the line before the code that will write to STDIO. For instance:

it "should print a copyright message" do
  $stdout.should_receive(:puts).with(/copyright/i)
  app = ApplicationController.new(%w[project_name])
end


it "should not print an error message" do
  $stdout.should_not_receive(:puts).with(/error/i)
  app = ApplicationController.new(%w[project_name])
end

That's an actual working RSpec from a project

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文