简体   繁体   English

如何在Ruby中存根STDOUT而不引发警告错误?

[英]How to stub STDOUT in Ruby without raising warning errors?

I've got a test that I want to run to test that I'm recieving output to STDOUT in Ruby. 我有一个测试,我想运行它以测试我正在接收Ruby中的STDOUT输出。

Right now my test looks like this: 现在,我的测试如下所示:

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

Which works and the test passes, but it feels very hacky and you'll get Ruby warning errors about an already initialized constant. 哪个可行,并且测试通过,但是感觉很hacky,并且您会收到有关已初始化常量的Ruby警告错误。

I know you can do this: 我知道您可以这样做:

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

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

But the string as you can see has two values that will change every time the test is run: the time (which I can fix with TimeCop but prefer not to) and the id of the run (which is set in Faraday, I could stub, but again: I'd prefer not to...) 但是,您可以看到,该字符串具有两个值,每次运行测试时都会改变:时间(我可以使用TimeCop修复但不愿意修改)和运行ID(在法拉第中设置),我可以进行存根,但再次:我不希望...)

So the crux of what am asking is: is there a way to do STDOUT.should_receive(:print).with(/[\\s\\S]+ INFO -- : get https:\\/\\/api.example.com\\/success/) or do a some sort of matching on the recieve? 因此,问题的症结在于:有没有办法做STDOUT.should_receive(:print).with(/[\\s\\S]+ INFO -- : get https:\\/\\/api.example.com\\/success/)还是在接收时进行某种匹配?

The full code is here if it helps: https://github.com/petems/oauth2/blob/faraday_debug/spec/oauth2/client_spec.rb#L123 如果有帮助的话,这里是完整的代码: https : //github.com/petems/oauth2/blob/faraday_debug/spec/oauth2/client_spec.rb#L123

Yes, you can do exactly what you proposed, as with accepts a regex as an argument, as in: 是的,你可以做的正是你提出什么, 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM