【问题标题】:How to stub STDOUT in Ruby without raising warning errors?如何在 Ruby 中存根 STDOUT 而不会引发警告错误?
【发布时间】:2014-02-11 15:05:47
【问题描述】:

我有一个要运行的测试来测试我正在接收输出到 Ruby 中的 STDOUT。

现在我的测试是这样的:

STDOUT.sync = true
@orig_stdout_constant = STDOUT
STDOUT  = StringIO.new

subject.request(:get, '/success')

expect(STDOUT.string).to include 'INFO -- : get https://api.example.com/success', 'INFO -- : get https://api.example.com/success'

STDOUT  = @orig_stdout_constant

哪个有效并且测试通过了,但是感觉很hacky,你会收到关于一个已经初始化的常量的Ruby警告错误。

我知道你可以这样做:

subject.request(:get, '/success')

STDOUT.should_receive(:print).with("I, [2014-02-11T14:55:00.282124 #650]  INFO -- : get https://api.example.com/success")

但是你可以看到的字符串有两个值会在每次运行测试时改变:时间(我可以用 TimeCop 修复,但我不想这样做)和运行的 id(在 Faraday 中设置,我可以存根,但再说一遍:我不想...)

所以我要问的关键是:有没有办法做STDOUT.should_receive(:print).with(/[\s\S]+ INFO -- : get https:\/\/api.example.com\/success/) 或在接收上做某种匹配?

如果有帮助,这里有完整的代码:https://github.com/petems/oauth2/blob/faraday_debug/spec/oauth2/client_spec.rb#L123

【问题讨论】:

    标签: ruby logging rspec stdout faraday


    【解决方案1】:

    是的,您可以完全按照您的建议去做,因为with 接受正则表达式作为参数,如下所示:

    describe "RSpec's #with method" do
      it "accepts a regex" do
        object = Object.new
        object.should_receive(:foo).with(/bar/)
        object.foo('foobar')
      end
    end
    

    【讨论】:

    • 啊,我想我上次运行它时只是语法错误或其他什么。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2013-04-20
    • 2017-07-13
    相关资源
    最近更新 更多