Test for warnings using RSpec

后端 未结 3 884
暗喜
暗喜 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:38

    This is my solution, I define a custom matcher has_warn

    require 'rspec'
    require 'stringio'
    
    module CustomMatchers
      class HasWarn
        def initialize(expected)
          @expected = expected
        end
    
        def matches?(given_proc)
          original_stderr = $stderr
          $stderr = StringIO.new
          given_proc.call
          @buffer = $stderr.string.strip
          @expected.include? @buffer.strip
        ensure
          $stderr = original_stderr
        end
    
        def supports_block_expectations?
          true
        end
    
        def failure_message_generator(to)
          %Q[expected #{to} get message:\n#{@expected.inspect}\nbut got:\n#{@buffer.inspect}]
        end
    
        def failure_message
          failure_message_generator 'to'
        end
    
        def failure_message_when_negated
          failure_message_generator 'not to'
        end
    
      end
    
      def has_warn(msg)
        HasWarn.new(msg)
      end
    end
    

    now you can use this function as follow after include the CustomMatchers:

    expect{ MyClass.new }.to has_warn("warning messages")
    

提交回复
热议问题