Class: Caricature::Expectations

Inherits:
Object
  • Object
show all
Defined in:
lib/caricature/expectation.rb

Overview

A collection of expectations with some methods to make it easier to work with them. It allows you to add and find expectations based on certain criteria.

Instance Method Summary collapse

Constructor Details

#initializeExpectations

initializes a new empty instance of the Expectation collection



8
9
10
11
# File 'lib/caricature/expectation.rb', line 8

def initialize
  @instance_expectations = []
  @class_expectations = []
end

Instance Method Details

#add_expectation(expectation, mode = :instance) ⇒ Object

Adds an expectation to this collection. From then on it can be found in the collection.



14
15
16
17
# File 'lib/caricature/expectation.rb', line 14

def add_expectation(expectation, mode=:instance)
  @instance_expectations << expectation unless mode == :class
  @class_expectations << expectation if mode == :class
end

#find(method_name, mode = :instance, *args) ⇒ Object

Finds an expectation in the collection. It matches by method_name first. Then it tries to figure out if you care about the arguments. You can say you don’t care by providing the symbol :any as first argument to this method. When you don’t care the first match is being returned When you specify arguments other than :any it will try to match the specified arguments in addition to the method name. It will then also return the first result it can find.



24
25
26
27
28
29
30
31
# File 'lib/caricature/expectation.rb', line 24

def find(method_name, mode=:instance, *args)
  expectations = mode == :class ? @class_expectations : @instance_expectations

  candidates = expectations.select { |exp| exp.method_name.to_s.underscore =~ /#{method_name}|#{method_name.to_s.underscore}/ }
  with_arguments_candidates = candidates.select { |exp| exp.args == args }
  
  with_arguments_candidates.first || candidates.select { |exp| exp.any_args?  }.first
end