Class: Object

Inherits:
BasicObject
Includes:
Minitest::Expectations
Defined in:
lib/minitest/mock.rb,
lib/minitest/spec.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods included from Minitest::Expectations

#assert_empty, #assert_equal, #assert_in_delta, #assert_in_epsilon, #assert_includes, #assert_instance_of, #assert_kind_of, #assert_match, #assert_nil, #assert_operator, #assert_output, #assert_raises, #assert_respond_to, #assert_same, #assert_silent, #assert_throws, #refute_empty, #refute_equal, #refute_in_delta, #refute_in_epsilon, #refute_includes, #refute_instance_of, #refute_kind_of, #refute_match, #refute_nil, #refute_operator, #refute_respond_to, #refute_same

Instance Method Details

#stub(name, val_or_callable, *block_args) ⇒ Object

Add a temporary stubbed method replacing name for the duration of the block. If val_or_callable responds to #call, then it returns the result of calling it, otherwise returns the value as-is. If stubbed method yields a block, block_args will be passed along. Cleans up the stub at the end of the block. The method name must exist before stubbing.

def test_stale_eh
  obj_under_test = Something.new
  refute obj_under_test.stale?

  Time.stub :now, Time.at(0) do
    assert obj_under_test.stale?
  end
end


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/minitest/mock.rb', line 201

def stub name, val_or_callable, *block_args
  new_name = "__minitest_stub__#{name}"

  metaclass = class << self; self; end

  if respond_to? name and not methods.map(&:to_s).include? name.to_s then
    metaclass.send :define_method, name do |*args|
      super(*args)
    end
  end

  metaclass.send :alias_method, new_name, name

  metaclass.send :define_method, name do |*args, &blk|
    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 self
ensure
  metaclass.send :undef_method, name
  metaclass.send :alias_method, name, new_name
  metaclass.send :undef_method, new_name
end