Module: TIMEx::Test

Extended by:
Test
Included in:
Test
Defined in:
lib/timex/test/virtual_clock.rb

Overview

Test helpers for controlling TIMEx time without real sleeps.

Installs a Clock::VirtualClock on the current thread and exposes helpers to advance it from nested code.

Instance Method Summary collapse

Instance Method Details

#advance(seconds) ⇒ Clock::VirtualClock

Advances the active Clock::VirtualClock by seconds.

Parameters:

  • seconds (Numeric)

    delta in seconds

Returns:

Raises:



39
40
41
42
43
# File 'lib/timex/test/virtual_clock.rb', line 39

def advance(seconds)
  clock = Thread.current.thread_variable_get(:timex_test_clock) ||
          raise("call inside TIMEx::Test.with_virtual_clock { ... }")
  clock.advance(seconds)
end

#freeze_timeObject



46
47
48
# File 'lib/timex/test/virtual_clock.rb', line 46

def freeze_time(&)
  with_virtual_clock(&)
end

#with_virtual_clock(start_ns: 0) {|clock| ... } ⇒ Object

Note:

Also sets :timex_test_clock so #advance can find the active clock without threading the object through call sites.

Installs a Clock::VirtualClock for the block and yields it for manual control.

Parameters:

  • start_ns (Integer) (defaults to: 0)

    initial monotonic nanoseconds for the virtual clock

Yield Parameters:

Returns:

  • (Object)

    the block’s return value



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/timex/test/virtual_clock.rb', line 22

def with_virtual_clock(start_ns: 0)
  previous_clock = Thread.current.thread_variable_get(:timex_clock)
  previous_test_clock = Thread.current.thread_variable_get(:timex_test_clock)
  clock = Clock::VirtualClock.new(monotonic_ns: start_ns)
  Thread.current.thread_variable_set(:timex_clock, clock)
  Thread.current.thread_variable_set(:timex_test_clock, clock)
  yield clock
ensure
  Thread.current.thread_variable_set(:timex_clock, previous_clock)
  Thread.current.thread_variable_set(:timex_test_clock, previous_test_clock)
end