Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Warn on RSpec comparisons between any time-like objects which may be sensitive to microsecond fluctuations in certain environments.
# This monkey patch modifies the RSpec `eq` matcher to suggest the `be_within`
# matcher instead when two time instances are being compared because equality
# comparison are inherently brittle on some operating systems like macOS so
# they may trigger false negatives.
module TimeComparisonWarning
def failure_message
msg = super
if [expected, actual].any? { |obj| obj.respond_to?(:strftime) }
msg << "\n"
msg << <<~STRING
WARNING: Comparing time instances with eq can be brittle.
Try to use be_within(0.1).of(expected) to allow for microsecond fluctuations.
STRING
end
end
end
class RSpec::Matchers::BuiltIn::Eq
prepend TimeComparisonWarning
end
class RSpec::Matchers::BuiltIn::Eql
prepend TimeComparisonWarning
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment