【问题标题】:Capturing STDOUT in RSpec在 RSpec 中捕获 STDOUT
【发布时间】:2016-05-19 05:15:28
【问题描述】:

我是 Ruby 单元测试的新手,在创建检查 STDOUT 的规范时遇到了一些麻烦。如果我正在测试的代码在类/方法中,我知道如何测试 STDOUT,但我只想测试来自不在类或方法中的常规 Ruby 文件的 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!

我以为我可以使用 $stdoutmy_file.rb 捕获 STDOUT,但这不起作用。输出一直说什么都没有。我发现这篇文章谈到了通过StringIOTesting STDOUT output in Rspec捕获输出

但这种方法对我不起作用。我做错了什么?

谢谢!

【问题讨论】:

    标签: ruby unit-testing rspec


    【解决方案1】:

    当您在测试运行之前将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
    

    【讨论】:

    • 谢谢!像魅力一样工作。下次会记住的。
    • 如果@Uzbekjon 回答了您的问题,请点击复选图标接受他的回答。请参阅meta.stackexchange.com/questions/5234/… 了解更多信息。
    • 此解决方案有效,但如果您有多个具有不同标准输出输出的测试,则第一个测试的输出会干扰第二个测试的输出。
    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2012-02-29
    • 2019-11-14
    • 2013-01-12
    相关资源
    最近更新 更多