在 RSpec 中捕获 STDOUT [英] Capturing STDOUT in RSpec

查看:43
本文介绍了在 RSpec 中捕获 STDOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 单元测试的新手,在创建将检查 STDOUT 的规范时遇到了一些问题.如果我正在测试的代码在类/方法中,我知道如何测试 STDOUT,但我只想测试来自不在类或方法中的常规 Ruby 文件的 puts 语句.

I'm new to unit testing in Ruby and I'm having some trouble creating a spec that will check for STDOUT. I know how to test STDOUT if the code I'm testing is within a Class/Method, but I want to just test a puts statement coming from a regular Ruby file that's not within a Class or Method.

这是来自 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规格

I thought I can just use $stdout to capture the STDOUT from my_file.rb but that didn't work. The output keeps saying its nothing. I found this post that speaks about capturing output via StringIO Testing STDOUT output in Rspec

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

But that method didn't work for me. What am I doing wrong?

谢谢!

推荐答案

当您将 my_file.rb 包含在顶部,在您之前测试已经运行.将其包含在您的测试中.

Your puts method is called when you included the my_file.rb right at the top, before your tests have run. Include it within your test.

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

这篇关于在 RSpec 中捕获 STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆