Skip to content

Commit

Permalink
Constrain actual in be_within matcher to values that respond to -
Browse files Browse the repository at this point in the history
instead of requiring a specific type.

- `Time`, for example, is a legit alternative.
- Fixes issue introduced by #145
  • Loading branch information
dchelimsky committed Jul 8, 2012
1 parent 705ddc5 commit 1d2cc1f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 4 additions & 4 deletions lib/rspec/matchers/built_in/be_within.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ def initialize(delta)


def matches?(actual) def matches?(actual)
@actual = actual @actual = actual
raise needs_expected unless defined? @expected raise needs_expected unless defined? @expected
raise needs_numeric unless @actual.is_a? Numeric raise needs_subtractable unless @actual.respond_to? :-
(@actual - @expected).abs <= @delta (@actual - @expected).abs <= @delta
end end


Expand All @@ -32,8 +32,8 @@ def description


private private


def needs_numeric def needs_subtractable
ArgumentError.new "The actual value (#{@actual.inspect}) must be of a `Numeric` type" ArgumentError.new "The actual value (#{@actual.inspect}) must respond to `-`"
end end


def needs_expected def needs_expected
Expand Down
8 changes: 6 additions & 2 deletions spec/rspec/matchers/be_within_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -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" matcher.failure_message_for_should_not.should == "expected 5.49 not to be within 0.5 of 5.0"
end end


it "works with Time" do
Time.now.should be_within(0.001).of(Time.now)
end

it "provides a description" do it "provides a description" do
matcher = be_within(0.5).of(5.0) matcher = be_within(0.5).of(5.0)
matcher.matches?(5.1) matcher.matches?(5.1)
Expand All @@ -62,9 +66,9 @@ module Matchers
) )
end 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( 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
end end
Expand Down

0 comments on commit 1d2cc1f

Please sign in to comment.