Class: ActiveSupport::Testing::SimpleStubs

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/testing/time_helpers.rb

Overview

Manages stubs for TimeHelpers

Defined Under Namespace

Classes: Stub

Instance Method Summary collapse

Constructor Details

#initializeSimpleStubs

Returns a new instance of SimpleStubs.



13
14
15
# File 'lib/active_support/testing/time_helpers.rb', line 13

def initialize
  @stubs = Concurrent::Map.new { |h, k| h[k] = {} }
end

Instance Method Details

#stub_object(object, method_name, &block) ⇒ Object

Stubs object.method_name with the given block If the method is already stubbed, remove that stub so that removing this stub will restore the original implementation.

Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
target = Time.zone.local(2004, 11, 24, 1, 4, 44)
simple_stubs.stub_object(Time, :now) { at(target.to_i) }
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00


24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/active_support/testing/time_helpers.rb', line 24

def stub_object(object, method_name, &block)
  if stub = stubbing(object, method_name)
    unstub_object(stub)
  end

  new_name = "__simple_stub__#{method_name}"

  @stubs[object.object_id][method_name] = Stub.new(object, method_name, new_name)

  object.singleton_class.alias_method new_name, method_name
  object.define_singleton_method(method_name, &block)
end

#stubbed?Boolean

Returns true if any stubs are set, false if there are none

Returns:

  • (Boolean)


54
55
56
# File 'lib/active_support/testing/time_helpers.rb', line 54

def stubbed?
  !@stubs.empty?
end

#stubbing(object, method_name) ⇒ Object

Returns the Stub for object#method_name (nil if it is not stubbed)



49
50
51
# File 'lib/active_support/testing/time_helpers.rb', line 49

def stubbing(object, method_name)
  @stubs[object.object_id][method_name]
end

#unstub_all!Object

Remove all object-method stubs held by this instance



38
39
40
41
42
43
44
45
# File 'lib/active_support/testing/time_helpers.rb', line 38

def unstub_all!
  @stubs.each_value do |object_stubs|
    object_stubs.each_value do |stub|
      unstub_object(stub)
    end
  end
  @stubs.clear
end