From 675115da39029770a353092194169e1119d7444e Mon Sep 17 00:00:00 2001 From: Su Zhang Date: Wed, 16 May 2012 23:32:31 -0400 Subject: [PATCH] Fix confusing error message in `be_within` This is a patch for the following issue: https://github.com/rspec/rspec-expectations/issues/92 It is possible to have duck typing for numerical operations, but the minus sign is often used for other operations as well such as the set difference that Array#- performs. In that case, even if it does not fail on the :- method, it will probably fail on the subsequent :abs and :<= calls. --- lib/rspec/matchers/built_in/be_within.rb | 3 +++ spec/rspec/matchers/be_within_spec.rb | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/lib/rspec/matchers/built_in/be_within.rb b/lib/rspec/matchers/built_in/be_within.rb index b492e90a6..ef43a804b 100644 --- a/lib/rspec/matchers/built_in/be_within.rb +++ b/lib/rspec/matchers/built_in/be_within.rb @@ -14,6 +14,9 @@ def matches?(actual) unless defined?(@expected) raise ArgumentError.new("You must set an expected value using #of: be_within(#{delta}).of(expected_value)") end + unless actual.is_a? Numeric + raise ArgumentError, "Expected a numeric value be within #{delta} of #{expected} but got #{actual.inspect}" + end (super(actual) - expected).abs <= delta end diff --git a/spec/rspec/matchers/be_within_spec.rb b/spec/rspec/matchers/be_within_spec.rb index 1d312bdcd..72968abec 100644 --- a/spec/rspec/matchers/be_within_spec.rb +++ b/spec/rspec/matchers/be_within_spec.rb @@ -59,6 +59,10 @@ module Matchers matcher = be_within(0.5) expect { matcher.matches?(5.1) }.to raise_error(ArgumentError, /must set an expected value using #of/) end + + it "raises an error if the actual value is not numeric" do + expect { be_within(0.1).of(0).matches?(nil) }.to raise_error(ArgumentError, /Expected a numeric value be within/) + end end end end