File: be_within.rb

package info (click to toggle)
ruby-rspec-expectations 2.14.2-1~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 920 kB
  • sloc: ruby: 8,202; makefile: 4
file content (55 lines) | stat: -rw-r--r-- 1,358 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module RSpec
  module Matchers
    module BuiltIn
      class BeWithin
        def initialize(delta)
          @delta = delta
        end

        def matches?(actual)
          @actual = actual
          raise needs_expected     unless defined? @expected
          raise needs_subtractable unless @actual.respond_to? :-
          (@actual - @expected).abs <= @tolerance
        end
        alias == matches?

        def of(expected)
          @expected  = expected
          @tolerance = @delta
          @unit      = ''
          self
        end

        def percent_of(expected)
          @expected  = expected
          @tolerance = @delta * @expected.abs / 100.0
          @unit      = '%'
          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}#{@unit} of #{@expected}"
        end

        private

        def needs_subtractable
          ArgumentError.new "The actual value (#{@actual.inspect}) must respond to `-`"
        end

        def needs_expected
          ArgumentError.new "You must set an expected value using #of: be_within(#{@delta}).of(expected_value)"
        end
      end
    end
  end
end