Sha256: 09696f188145be35f45f2ab3f2db191af91be773419720a79203d8eb3817835d

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

module RSpec
  module Matchers
    module BuiltIn
      class BeWithin
        include Composable

        def initialize(delta)
          @delta = delta
        end

        def matches?(actual)
          @actual = actual
          raise needs_expected unless defined? @expected
          numeric? && (@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
          "expected #{@actual.inspect} to #{description}#{not_numeric_clause}"
        end

        def failure_message_when_negated
          "expected #{@actual.inspect} not to #{description}"
        end

        def description
          "be within #{@delta}#{@unit} of #{@expected}"
        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

1 entries across 1 versions & 1 rubygems

Version Path
rspec-expectations-3.0.0.beta2 lib/rspec/matchers/built_in/be_within.rb