ruby - 在 RSpec 中捕获 STDOUT

标签 ruby unit-testing rspec

我是 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,但这没有用。输出一直说什么都没有。我发现这篇文章谈到通过 StringIO Testing STDOUT output in Rspec 捕获输出

但是那个方法对我不起作用。我做错了什么?

谢谢!

最佳答案

当您在顶部包含 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

关于ruby - 在 RSpec 中捕获 STDOUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309874/

相关文章:

ruby-on-rails - 运行 PrivatePub.publish_to 时出现 EOF 文件结尾错误

ruby - 使用 RSpec 进行问题 stub

java - 测试DatagramSockets的传输

java - 如何对自定义 Wicket 组件进行单元测试

unit-testing - 测试驱动开发和开放/封闭原则如何协同工作?

ruby-on-rails - 当 Guard 在监视文件中运行规范时,Rspec/Capybara "feature"方法未定义,手动运行时有效

regex - Ruby 重复值正则表达式匹配,但更聪明的是向前看

ruby - RSpec:字符串应该在数组中

ruby-on-rails - 如何在 rails 3 中 stub find_each 进行 rspec 测试

ruby-on-rails - 通过 Capistrano 任务启动具有/特定队列的多个延迟作业工作人员