Sha256: ea5803464f3a59acd0966903f33c346ac0d9bdd721c36ddf726fb23f91e7441f

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

module RR
  module Expectations
    class TimesCalledExpectation
      attr_reader :times, :times_called
      
      def initialize(times=nil, &time_condition_block)
        raise ArgumentError, "Cannot pass in both an argument and a block" if times && time_condition_block
        @times = times || time_condition_block
        @times_called = 0
        @verify_backtrace = caller[1..-1]
      end

      def verify_input
        @times_called += 1
        verify_input_error if @times.is_a?(Integer) && @times_called > @times
        verify_input_error if @times.is_a?(Range) && @times_called > @times.end
        return
      end

      def verify
        return true if @times.is_a?(Integer) && @times == @times_called
        return true if @times.is_a?(Proc) && @times.call(@times_called)
        return true if @times.is_a?(Range) && @times.include?(@times_called)
        return false
      end

      def verify!
        unless verify
          if @verify_backtrace
            error = Errors::TimesCalledError.new(error_message)
            error.backtrace = @verify_backtrace
            raise error
          else
            raise Errors::TimesCalledError, error_message
          end
        end
      end

      protected
      def verify_input_error
        raise Errors::TimesCalledError, error_message
      end

      def error_message
        time_casing = (@times_called == 1) ? "time" : "times"
        "Called #{@times_called.inspect} #{time_casing}. Expected #{@times.inspect}."
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rr-0.1.5 lib/rr/expectations/times_called_expectation.rb
rr-0.1.6 lib/rr/expectations/times_called_expectation.rb