Method: Minitest::Moar::Stubbing#__stub__

Defined in:
lib/minitest/moar/stubbing.rb

#__stub__(obj, name, val_or_callable = nil, *block_args, &block) ⇒ Object



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
# File 'lib/minitest/moar/stubbing.rb', line 25

def __stub__ obj, name, val_or_callable = nil, *block_args, &block
  new_name = "__minitest_stub__#{name}"

  @invocations ||= Hash.new { |h, k| h[k] = Hash.new { |_h, _k| _h[_k] = 0 } }

  invoker = Proc.new { |klass, name| @invocations[klass][name] += 1 }

  obj.send :alias_method, new_name, name

  # Module.method(:define_method).bind(klass).call(name) do |*args, &blk|
  obj.send :define_method, name do |*args, &blk|
    if ::Class === self
      invoker.call(self, name)
    else
      klass = Kernel.instance_method(:class).bind(self).call
      invoker.call("Instance of #{klass}", name)
    end

    ret = if val_or_callable.respond_to? :call then
      val_or_callable.call(*args)
    else
      val_or_callable
    end

    blk.call(*block_args) if blk

    ret
  end

  yield obj
ensure
  obj.send :undef_method, name
  obj.send :alias_method, name, new_name
  obj.send :undef_method, new_name
end