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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More