aboutsummaryrefslogtreecommitdiffstats
path: root/spec/mspec/lib/mspec/matchers/complain.rb
blob: 1313215156ffcbf64ac0489e9238bac903a8a0f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require 'mspec/helpers/io'

class ComplainMatcher
  def initialize(complaint)
    @complaint = complaint
  end

  def matches?(proc)
    @saved_err = $stderr
    @stderr = $stderr = IOStub.new
    @verbose = $VERBOSE
    $VERBOSE = false

    proc.call

    unless @complaint.nil?
      case @complaint
      when Regexp
        return false unless $stderr =~ @complaint
      else
        return false unless $stderr == @complaint
      end
    end

    return $stderr.empty? ? false : true
  ensure
    $VERBOSE = @verbose
    $stderr = @saved_err
  end

  def failure_message
    if @complaint.nil?
      ["Expected a warning", "but received none"]
    elsif @complaint.kind_of? Regexp
      ["Expected warning to match: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
    else
      ["Expected warning: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
    end
  end

  def negative_failure_message
    if @complaint.nil?
      ["Unexpected warning: ", @stderr.chomp.inspect]
    elsif @complaint.kind_of? Regexp
      ["Expected warning not to match: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
    else
      ["Expected warning: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
    end
  end
end

class Object
  def complain(complaint=nil)
    ComplainMatcher.new(complaint)
  end
end