Sha256: 038377567b737b6bc1e98b4daff87ac5a0517def3f484849f131efc873d10d80

Contents?: true

Size: 1.89 KB

Versions: 8

Compression:

Stored size: 1.89 KB

Contents

module RSpec
  module Matchers
    module BuiltIn
      # @api private
      # Provides the implementation for `be_within`.
      # Not intended to be instantiated directly.
      class BeWithin
        include Composable

        def initialize(delta)
          @delta = delta
        end

        # @api public
        # Sets the expected value.
        def of(expected)
          @expected  = expected
          @tolerance = @delta
          @unit      = ''
          self
        end

        # @api public
        # Sets the expected value, and makes the matcher do
        # a percent comparison.
        def percent_of(expected)
          @expected  = expected
          @tolerance = @delta * @expected.abs / 100.0
          @unit      = '%'
          self
        end

        # @private
        def matches?(actual)
          @actual = actual
          raise needs_expected unless defined? @expected
          numeric? && (@actual - @expected).abs <= @tolerance
        end

        # @api private
        # @return [String]
        def failure_message
          "expected #{@actual.inspect} to #{description}#{not_numeric_clause}"
        end

        # @api private
        # @return [String]
        def failure_message_when_negated
          "expected #{@actual.inspect} not to #{description}"
        end

        # @api private
        # @return [String]
        def description
          "be within #{@delta}#{@unit} of #{@expected}"
        end

        # @private
        def supports_block_expectations?
          false
        end

      private

        def numeric?
          @actual.respond_to?(:-)
        end

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

        def not_numeric_clause
          ", but it could not be treated as a numeric value" unless numeric?
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
rspec-expectations-3.0.4 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-3.0.3 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-3.0.2 lib/rspec/matchers/built_in/be_within.rb
whos_dated_who-0.1.0 vendor/bundle/gems/rspec-expectations-3.0.1/lib/rspec/matchers/built_in/be_within.rb
whos_dated_who-0.0.1 vendor/bundle/gems/rspec-expectations-3.0.1/lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-3.0.1 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-3.0.0 lib/rspec/matchers/built_in/be_within.rb
rspec-expectations-3.0.0.rc1 lib/rspec/matchers/built_in/be_within.rb