是否有可能使用RSpec测试
Ruby的警告?
像这样:
class MyClass def initialize warn "Something is wrong" end end it "should warn" do MyClass.new.should warn("Something is wrong") end
解决方法
warn在Kernel中定义,它包含在每个对象中.如果您在初始化期间未提出警告,则可以指定如下警告:
obj = SomeClass.new obj.should_receive(:warn).with("Some Message") obj.method_that_warns
在initialize方法中引发警告是非常复杂的.如果必须这样做,您可以为$stderr交换一个伪IO对象并检查它.请务必在示例后恢复它
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