-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathinvoke.rb
98 lines (73 loc) · 1.92 KB
/
invoke.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# frozen_string_literal: true
require "active_support/core_ext/module/delegation"
class Matchers::Invoke
include RSpec::Matchers::Composable
delegate :failure_message,
:failure_message_when_negated,
to: :received_matcher
def initialize(expected_method)
@expected_method = expected_method
end
def matches?(event_proc)
raise(ArgumentError, "missing '.on'") unless defined?(@expected_recipient)
allow(@expected_recipient).to receive(@expected_method)
allow(@expected_recipient).to receive_expected
event_proc.call
received_matcher.matches?(@expected_recipient)
end
def on(expected_recipient)
@expected_recipient = expected_recipient
self
end
def with(*expected_arguments)
@expected_arguments = expected_arguments
self
end
def and_return(*return_arguments)
@return_arguments = return_arguments
self
end
def and_call_original
@and_call_original = true
self
end
def twice
@times = 2
self
end
def once
@times = 1
self
end
def supports_block_expectations?
true
end
private
def receive_expected
receive_expected = receive(@expected_method)
if defined?(@return_arguments)
receive_expected = receive_expected.and_return(*@return_arguments)
end
if defined?(@and_call_original)
receive_expected = receive_expected.and_call_original
end
receive_expected
end
def allow(target)
RSpec::Mocks::AllowanceTarget.new(target)
end
def receive(method_name)
RSpec::Mocks::Matchers::Receive.new(method_name, nil)
end
def received_matcher
@received_matcher ||=
begin
matcher = RSpec::Mocks::Matchers::HaveReceived.new(@expected_method)
if defined?(@expected_arguments)
matcher = matcher.with(*@expected_arguments)
end
matcher = matcher.exactly(@times).times if defined?(@times)
matcher
end
end
end