Module: Postburner::TimeHelpers

Included in:
NullQueue, TimeTravelTestQueue
Defined in:
lib/postburner/time_helpers.rb

Overview

Note:

Requires ActiveSupport::Testing::TimeHelpers (Rails testing framework)

Note:

Time travel affects global time via Time.stub - use only in test environments

Provides time travel utilities for testing without requiring test context.

This module wraps ActiveSupport::Testing::TimeHelpers to enable time travel from non-test contexts (like class methods or service objects). It creates a helper object extended with Rails’ TimeHelpers and delegates time travel operations to it.

## Usage

Examples:

Basic time travel

include Postburner::TimeHelpers

travel_to(2.days.from_now) do
  # Code here executes as if it's 2 days in the future
  Time.current   # => 2 days from now (preferred in Rails)
  Time.zone.now  # => 2 days from now (equivalent)
end

In a class method

class MyService
  extend Postburner::TimeHelpers

  def self.process_scheduled_task(time)
    travel_to(time) do
      # Execute task at specified time
    end
  end
end

See Also:

  • ActiveSupport::Testing::TimeHelpers

Instance Method Summary collapse

Instance Method Details

#travel_to(time, &block) ⇒ Object

Travels to specified time for block execution using Rails time helpers.

Creates a helper object extended with ActiveSupport::Testing::TimeHelpers and uses it to stub global time. This is necessary for time travel outside of test method contexts where TimeHelpers aren’t available directly.

The travel_to call stubs Time globally (using Time.stub), so all time-based operations within the block execute as if they’re happening at the specified time. After the block completes, time returns to normal.

Examples:

Travel to specific time

travel_to(Time.zone.parse('2025-12-25 00:00:00')) do
  puts Time.current   # => 2025-12-25 00:00:00 (preferred)
  puts Time.zone.now  # => 2025-12-25 00:00:00 (equivalent)
end

Travel relative to now

travel_to(1.hour.from_now) do
  # Execute code as if 1 hour has passed
end

Parameters:

  • time (Time, DateTime, ActiveSupport::TimeWithZone)

    The time to travel to

  • block (Proc)

    Block to execute at the specified time

Returns:

  • (Object)

    The return value of the block

Raises:

  • (RuntimeError)

    if ActiveSupport::Testing::TimeHelpers not available



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/postburner/time_helpers.rb', line 67

def travel_to(time, &block)
  unless defined?(ActiveSupport::Testing::TimeHelpers)
    raise <<~ERROR
      ActiveSupport::Testing::TimeHelpers not available.
      Postburner::TimeHelpers requires Rails testing helpers for time travel.
    ERROR
  end

  helper = Object.new.extend(ActiveSupport::Testing::TimeHelpers)
  helper.travel_to(time, &block)
end