使用 RSpec 测试警告 [英] Test for warnings using RSpec
本文介绍了使用 RSpec 测试警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 RSpec 测试 Ruby 中的警告?
Is it somehow possible to test warnings i Ruby using RSpec?
像这样:
class MyClass
def initialize
warn "Something is wrong"
end
end
it "should warn" do
MyClass.new.should warn("Something is wrong")
end
推荐答案
warn
定义在 Kernel
中,它包含在每个对象中.如果您没有在初始化期间发出警告,则可以指定如下警告:
warn
is defined in Kernel
, which is included in every object. If you weren't raising the warning during initialization, you could specify a warning like this:
obj = SomeClass.new
obj.should_receive(:warn).with("Some Message")
obj.method_that_warns
指定在 initialize
方法中引发的警告相当复杂.如果必须这样做,您可以为 $stderr
交换一个假的 IO
对象并检查它.做完例子一定要恢复
Spec'ing a warning raised in the initialize
method is quite more complex. If it must be done, you can swap in a fake IO
object for $stderr
and inspect it. Just be sure to restore it after the example
class MyClass
def initialize
warn "Something is wrong"
end
end
describe MyClass do
before do
@orig_stderr = $stderr
$stderr = StringIO.new
end
it "warns on initialization" do
MyClass.new
$stderr.rewind
$stderr.string.chomp.should eq("Something is wrong")
end
after do
$stderr = @orig_stderr
end
end
这篇关于使用 RSpec 测试警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文