Module: Phronomy::Testing::SchedulerHelpers

Defined in:
lib/phronomy/testing/scheduler_helpers.rb

Overview

RSpec helper module that provides a deterministic Runtime backed by Runtime::FakeScheduler.

Include this module in your RSpec describe/context blocks and call #with_fake_scheduler to run a block of code inside a fully synchronous, event-logged runtime.

Examples:

Basic usage (no clock)

include Phronomy::Testing::SchedulerHelpers

it "records completed events" do
  with_fake_scheduler do |sched|
    Phronomy::Runtime.instance.spawn(name: "my-task") { 42 }
    expect(sched.event_log.map { |e| e[:type] }).to include(:completed)
  end
end

With a FakeClock

include Phronomy::Testing::SchedulerHelpers

it "surfaces pending timers" do
  clock = Phronomy::Testing::FakeClock.new
  with_fake_scheduler(clock: clock) do |sched|
    clock.schedule(seconds: 5) { :fired }
    expect(sched.pending_timers.first[:fire_at]).to eq(5.0)
  end
end

Instance Method Summary collapse

Instance Method Details

#with_fake_scheduler(clock: nil) {|scheduler, clock| ... } ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Run +block+ with a Runtime that uses Runtime::FakeScheduler.

The global runtime is replaced for the duration of the block and restored afterwards, whether the block raises or not.

Parameters:

  • clock (Phronomy::Testing::FakeClock, nil) (defaults to: nil)

    Optional fake clock to inject into the scheduler for timer support and event timestamping.

Yields:

Returns:

  • (Object)

    the return value of the block



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/phronomy/testing/scheduler_helpers.rb', line 45

def with_fake_scheduler(clock: nil)
  scheduler = Phronomy::Runtime::FakeScheduler.new
  scheduler.clock = clock if clock
  runtime = Phronomy::Runtime.new(scheduler: scheduler)
  original = Phronomy::Runtime.instance
  Phronomy::Runtime.instance = runtime
  begin
    yield scheduler, clock
  ensure
    Phronomy::Runtime.instance = original
  end
end