Module: Quickdraw::Matchers::ToReceive

Defined in:
lib/quickdraw/matchers/to_receive.rb

Instance Method Summary collapse

Instance Method Details

#to_receive(method_name, &expectation_block) ⇒ Object



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
# File 'lib/quickdraw/matchers/to_receive.rb', line 4

def to_receive(method_name, &expectation_block)
	__raise__ ::ArgumentError, "You can't use the `to_receive` matcher with a block expectation." if @block

	interceptor = ::Module.new

	# Define local variables so they're available from the block
	expectation = self
	context = @context

	interceptor.define_method(method_name) do |*args, **kwargs, &block|
		expectation.success!
		super_block = -> (*a, &b) { (a.length > 0) || b ? super(*a, &b) : super(*args, **kwargs, &block) }
		original_super = context.instance_variable_get(:@super)
		begin
			context.instance_variable_set(:@super, super_block)
			result = expectation_block&.call(*args, **kwargs, &block)
		ensure
			context.instance_variable_set(:@super, original_super)
		end

		interceptor.define_method(method_name) { |*a, **k, &b| super(*a, **k, &b) }
		result
	end

	value.singleton_class.prepend(interceptor)
end