Sha256: a02bffd1f8c33403f9e6ac7491fbd6cb2259387c2410b4e2b7117ba6b5566a59

Contents?: true

Size: 1.42 KB

Versions: 4

Compression:

Stored size: 1.42 KB

Contents

module RSpec
  module Matchers
    module BuiltIn
      class BeWithin
        include MatchAliases

        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

        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 supports_block_expectations?
          false
        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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rspec-expectations-2.99.2 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-2.99.1 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-2.99.0 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-2.99.0.rc1 lib/rspec/matchers/built_in/be_within.rb