Test for warnings using RSpec

后端 未结 3 886
暗喜
暗喜 2021-01-17 23:32

Is it somehow possible to test warnings i Ruby using RSpec?

Like this:

class MyClass
  def initialize
    warn \"Something is wrong\"
  end
end

it \         


        
3条回答
  •  花落未央
    2021-01-17 23:43

    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
    

    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
    

提交回复
热议问题