Skip to content

class Athena::Clock::Spec::MockClock
inherits Reference #

The mock clock is instantiated with a time and does not move forward on its own. The time is fixed until #sleep or #shift is called. This provides full control over what time the code assumes it's running with, ultimately making testing time-sensitive types much easier.

class ExpirationChecker
  def initialize(@clock : Athena::Clock::Interface); end

  def expired?(valid_until : Time) : Bool
    @clock.now > valid_until
  end
end

clock = ACLK::Spec::MockClock.new Time.utc 2023, 9, 16, 15, 20
expiration_checker = ExpirationChecker.new clock
valid_until = Time.utc 2023, 9, 16, 15, 25

# valid_until is in the future, so not expired
expiration_checker.expired?(valid_until).should be_false

# Sleep for 10 minutes, so time is now 2023-09-16 15:30:00,
# time is instantly changes as if 10 minutes really passed
clock.sleep 10.minutes

expiration_checker.expired?(valid_until).should be_true

# Time can also be shifted, either into the future or past
clock.shift minutes: -20

# valid_until is in the future again, so not expired
expiration_checker.expired?(valid_until).should be_false

Included modules

Athena::Clock::Interface

Constructors#

.new(now : Time = Time.local, location : Time::Location | Nil = nil)#

View source

Methods#

#in_location(location : Time::Location) : self#

Returns a new clock instance set to the provided location.

View source

#now : Time#

Returns the current time as determined by the clock.

View source

#shift(*, years : Int = 0, months : Int = 0, weeks : Int = 0, days : Int = 0, hours : Int = 0, minutes : Int = 0, seconds : Int = 0) : Nil#

Shifts the mocked time instance by the provided amount of time. Positive values shift into the future, while negative values shift into the past.

This method is essentially equivalent to calling #sleep with the same amount of time, but this method provides a better API in some cases.

View source

#sleep(span : Time::Span) : Nil#

Sleeps for the provided span of time.

View source

#sleep(seconds : Number) : Nil#

Sleeps for the provided amount of seconds.

View source