Last active
December 16, 2015 20:29
-
-
Save terrafied/5492630 to your computer and use it in GitHub Desktop.
RSpec matcher to allow for possible, not required, conditions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec/expectations' | |
# It would be better if we could change this to pending on the fly, but that happens in a higher scope, | |
# so there's nothing but "pass" or "fail" | |
RSpec::Matchers.define :maybe_match do |expected| | |
match do |actual| | |
true | |
end | |
description do |actual| | |
if actual == expected | |
"FUZZY PASS: #{actual} actually matches #{expected}" | |
else | |
"FUZZY FAIL: #{actual} does not match #{expected}, but probably should" | |
end | |
end | |
end | |
RSpec::Matchers.define :maybe_be_within do |delta| | |
chain :of do |expected| | |
@expected = expected | |
end | |
match do |actual| | |
true | |
end | |
description do |actual| | |
distance = (actual - @expected).abs | |
if distance <= delta | |
"FUZZY PASS: #{actual} is within #{delta} of #{expected}" | |
else | |
"FUZZY FAIL: #{actual} is #{distance} away from #{expected} but probably should be within #{delta}" | |
end | |
end | |
end | |
# specify { "this".should maybe_match "that"} | |
# --> this does not match that, but probably should |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment