Class: Object

Inherits:
BasicObject
Defined in:
lib/expect-call.rb

Instance Method Summary collapse

Instance Method Details

#expect_call(method_name, params, val_or_callable = nil, &block) ⇒ Object



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
# File 'lib/expect-call.rb', line 2

def expect_call( method_name, params, val_or_callable = nil, &block )
  context = block.binding.eval( 'self' )

  if context.respond_to?( :assert )
    assert_method = context.method( :assert )
  else
    assert_method = Proc.new do |condition, message|
      raise RuntimeError, "expect-call assertion\n#{ message }" unless condition
    end
  end
  
  metaclass = class << self; self; end

  orig_method = nil

  if respond_to? method_name
    orig_method = method( method_name )
    metaclass.send :undef_method, method_name
  end

  clean_up = Proc.new do
    metaclass.send :undef_method, method_name
    if orig_method
      metaclass.send :define_method, method_name, orig_method
    end
  end

  was_called = false

  new_method = Proc.new do |*args|
    was_called = true
    clean_up.call

    assert_method.call params == args, <<-MSG % [ method_name, params.inspect, args.inspect ]
Method '%s' called with unexpected arguments
Expected: %s
  Actual: %s
    MSG

    if val_or_callable.respond_to?( :call )
      return val_or_callable.call( *args )
    end

    val_or_callable
  end

  metaclass.send :define_method, method_name, new_method

  yield

  assert_method.call was_called, "Method '%s' was not called" % [ method_name ]
ensure
  clean_up.call unless was_called
end