Skip to content
Browse files

be_within matcher to class

  • Loading branch information...
1 parent 93f6ac4 commit 148192bbb72d9f98721c4162c05f272e78a5f4ef @dchelimsky dchelimsky committed Oct 20, 2011
Showing with 36 additions and 25 deletions.
  1. +10 −0 lib/rspec/matchers.rb
  2. +26 −25 lib/rspec/matchers/be_within.rb
View
10 lib/rspec/matchers.rb
@@ -269,6 +269,16 @@ def be_an_instance_of(expected)
end
alias_method :be_instance_of, :be_an_instance_of
+
+ # Passes if actual == expected +/- delta
+ #
+ # == Examples
+ #
+ # result.should be_within(0.5).of(3.0)
+ # result.should_not be_within(0.5).of(3.0)
+ def be_within(delta)
+ BeWithin.new(delta)
+ end
end
end
View
51 lib/rspec/matchers/be_within.rb
@@ -1,35 +1,36 @@
module RSpec
module Matchers
- # Passes if actual == expected +/- delta
- #
- # == Examples
- #
- # result.should be_within(0.5).of(3.0)
- # result.should_not be_within(0.5).of(3.0)
- def be_within(delta)
- Matcher.new :be_within, delta do |_delta_|
- chain :of do |_expected_|
- @_expected = _expected_
- end
+ class BeWithin
+ include BaseMatcher
- match do |actual|
- unless defined?(@_expected)
- raise ArgumentError.new("You must set an expected value using #of: be_within(#{_delta_}).of(expected_value)")
- end
- (actual - @_expected).abs < _delta_
- end
+ attr_reader :delta
- failure_message_for_should do |actual|
- "expected #{actual} to #{description}"
- end
+ def initialize(delta)
+ @delta = delta
+ end
- failure_message_for_should_not do |actual|
- "expected #{actual} not to #{description}"
+ def matches?(actual)
+ unless defined?(@expected)
+ raise ArgumentError.new("You must set an expected value using #of: be_within(#{delta}).of(expected_value)")
end
+ (super(actual) - expected).abs < delta
+ end
- description do
- "be within #{_delta_} of #{@_expected}"
- end
+ def of(expected)
+ @expected = expected
+ self
+ end
+
+ def failure_message_for_should
+ "expected #{actual} to #{description}"
+ end
+
+ def failure_message_for_should_not
+ "expected #{actual} not to #{description}"
+ end
+
+ def description
+ "be within #{delta} of #{expected}"
end
end
end

0 comments on commit 148192b

Please sign in to comment.
Something went wrong with that request. Please try again.