forked from dchelimsky/rspec-stories
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operator_matcher.rb
executable file
·68 lines (54 loc) · 2.06 KB
/
operator_matcher.rb
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
57
58
59
60
61
62
63
64
65
66
67
68
module Spec
module Matchers
class OperatorMatcher
@operator_registry = {}
def self.register(klass, operator, matcher)
@operator_registry[klass] ||= {}
@operator_registry[klass][operator] = matcher
end
def self.get(klass, operator)
return @operator_registry[klass][operator] if @operator_registry[klass]
nil
end
def initialize(actual)
@actual = actual
end
def self.use_custom_matcher_or_delegate(operator)
define_method(operator) do |expected|
if matcher = OperatorMatcher.get(@actual.class, operator)
return @actual.send(::Spec::Matchers.last_should, matcher.new(expected))
else
::Spec::Matchers.last_matcher = self
@operator, @expected = operator, expected
__delegate_operator(@actual, operator, expected)
end
end
end
['==', '===', '=~', '>', '>=', '<', '<='].each do |operator|
use_custom_matcher_or_delegate operator
end
def fail_with_message(message)
Spec::Expectations.fail_with(message, @expected, @actual)
end
def description
"#{@operator} #{@expected.inspect}"
end
end
class PositiveOperatorMatcher < OperatorMatcher #:nodoc:
def __delegate_operator(actual, operator, expected)
return true if actual.__send__(operator, expected)
if ['==','===', '=~'].include?(operator)
fail_with_message("expected: #{expected.inspect},\n got: #{actual.inspect} (using #{operator})")
else
fail_with_message("expected: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}")
end
end
end
class NegativeOperatorMatcher < OperatorMatcher #:nodoc:
def __delegate_operator(actual, operator, expected)
return true unless actual.__send__(operator, expected)
return fail_with_message("expected not: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}")
end
end
end
end