Class: Grasshopper::Mock

Inherits:
Object
  • Object
show all
Defined in:
lib/grasshopper/mock.rb

Defined Under Namespace

Classes: AnyParams, MessageHeard

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMock

Returns a new instance of Mock.



3
4
5
# File 'lib/grasshopper/mock.rb', line 3

def initialize
  @verify_next = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(message, *args, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/grasshopper/mock.rb', line 11

def method_missing(message, *args, &block)
  request = MessageHeard.new(message, args)

  @messages ||= []
  if @verify_next
    if args.first.is_a? AnyParams
      index = @messages.index { |heard| request.message == heard.message }
    else
      index = @messages.index { |heard| request == heard }
    end
    if index.nil?
      raise "Should have seen an invocation of #{message}(#{args.join(", ")})\n#{@messages.inspect}"
    end
    @messages.delete_at(index || @messages.length)
  else
    @messages << request
  end
  nil
end

Class Method Details

.verify(mock) ⇒ Object



33
34
35
36
37
# File 'lib/grasshopper/mock.rb', line 33

def self.verify mock
  raise "Not a #{self.class}" unless mock.is_a? Grasshopper::Mock
  mock.verify_next
  mock
end

Instance Method Details

#verify_nextObject



7
8
9
# File 'lib/grasshopper/mock.rb', line 7

def verify_next
  @verify_next = true
end