Permalink
Browse files

Constrain `actual` in `be_within` matcher to values that respond to `-`

instead of requiring a specific type.

- `Time`, for example, is a legit alternative.
- Fixes issue introduced by #145
  • Loading branch information...
1 parent 705ddc5 commit 1d2cc1fa64503f8c124518104a54d7f0f3e4b167 @dchelimsky dchelimsky committed Jul 8, 2012
Showing with 10 additions and 6 deletions.
  1. +4 −4 lib/rspec/matchers/built_in/be_within.rb
  2. +6 −2 spec/rspec/matchers/be_within_spec.rb
@@ -8,8 +8,8 @@ def initialize(delta)
def matches?(actual)
@actual = actual
- raise needs_expected unless defined? @expected
- raise needs_numeric unless @actual.is_a? Numeric
+ raise needs_expected unless defined? @expected
+ raise needs_subtractable unless @actual.respond_to? :-
(@actual - @expected).abs <= @delta
end
@@ -32,8 +32,8 @@ def description
private
- def needs_numeric
- ArgumentError.new "The actual value (#{@actual.inspect}) must be of a `Numeric` type"
+ def needs_subtractable
+ ArgumentError.new "The actual value (#{@actual.inspect}) must respond to `-`"
end
def needs_expected
@@ -49,6 +49,10 @@ module Matchers
matcher.failure_message_for_should_not.should == "expected 5.49 not to be within 0.5 of 5.0"
end
+ it "works with Time" do
+ Time.now.should be_within(0.001).of(Time.now)
+ end
+
it "provides a description" do
matcher = be_within(0.5).of(5.0)
matcher.matches?(5.1)
@@ -62,9 +66,9 @@ module Matchers
)
end
- it "raises an error if the actual value is not of a Numeric type" do
+ it "raises an error if the actual does not respond to :-" do
expect { be_within(0.1).of(0).matches?(nil) }.to raise_error(
- ArgumentError, /The actual value \(nil\) must be of a `Numeric` type/
+ ArgumentError, /The actual value \(nil\) must respond to `-`/
)
end
end

0 comments on commit 1d2cc1f

Please sign in to comment.