DEV Community

Augusts Bautra
Augusts Bautra

Posted on • Edited on

Using the semi-secret `within` matcher in RSpec

Sometimes, it can be tricky to write asserts for values that are nondeterministic, but flicker by a negligible amount, especially when working with time.

While I agree that the first line of defence should be to seek to freeze the time, sometimes it's not an option. Enter the "fuzzy" within matcher.

# bad
is_expected.to(
  be < execution_start.since(5.seconds)
  .and(be >= execution_start)
)

# good
is_expected.to be_within(5.seconds).of(execution_start)
Enter fullscreen mode Exit fullscreen mode

Docs on this matcher are rather limited and fail to mention that it can also be used in collections and arguments by omitting the be_ part.

is_expected.to(
  change { record.field }.to(within(5.seconds).of(some_time))
)

expect(SomeClass).to(
  have_received(:call)
  .with(stamp: within(5.seconds).of(some_time))
  .once
)
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay