Module: Megatest::Stubs

Included in:
Test
Defined in:
lib/megatest/stubs.rb

Instance Method Summary collapse

Instance Method Details

#stub(object, method, proc = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/megatest/stubs.rb', line 41

def stub(object, method, proc = nil)
  stubber = ::Megatest::Stubber.for(object)
  teardown = stubber.stub_method(method, proc)

  if block_given?
    begin
      yield
    ensure
      teardown.call
    end
  else
    @__m.on_teardown << teardown
  end
end

#stub_any_instance_of(klass, method, proc = nil) ⇒ Object

Raises:

  • (ArgumentError)


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/megatest/stubs.rb', line 56

def stub_any_instance_of(klass, method, proc = nil)
  raise ArgumentError, "stub_any_instance_of expects a Module or Class" unless Module === klass

  stubber = ::Megatest::Stubber.for_class(klass)
  teardown = stubber.stub_method(method, proc)

  if block_given?
    begin
      yield
    ensure
      teardown.call
    end
  else
    @__m.on_teardown << teardown
  end
end

#stub_const(mod, constant, new_value, exists: true) ⇒ Object



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
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/megatest/stubs.rb', line 73

def stub_const(mod, constant, new_value, exists: true)
  if exists
    old_value = mod.const_get(constant, false)
    teardown = -> do
      mod.send(:remove_const, constant) if mod.const_defined?(constant, false)
      mod.const_set(constant, old_value)
    end
  else
    if mod.const_defined?(constant)
      raise NameError, "already defined constant #{constant} in #{mod.name || mod.inspect}"
    end

    teardown = -> do
      mod.send(:remove_const, constant) if mod.const_defined?(constant, false)
    end
  end

  apply = -> do
    mod.send(:remove_const, constant) if exists
    mod.const_set(constant, new_value)
  end

  if block_given?
    begin
      apply.call
      yield
    ensure
      teardown.call
    end
  else
    begin
      apply.call
    rescue
      teardown.call
      raise
    end
    @__m.on_teardown << teardown
  end
end