Module: Imitate

Defined in:
lib/imitate.rb

Constant Summary collapse

MOCKED =
[]

Class Method Summary collapse

Class Method Details

.mock(name, &block) ⇒ Object

Create class with a given name. If name contains any package, which doesn’t exist yet, its created along the way.

Example: mock_class(‘ActiveRecord::Base’) mock_class(‘Foo’) do

def bar
  'bar'
end

end

Foo.new.bar #= ‘bar’

Parameters:

  • Name (String)

    of the class to be created.

  • Optional (Proc)

    block to be instance evaluated on new class.



25
26
27
28
29
# File 'lib/imitate.rb', line 25

def mock(name, &block)
  process_name(name) do |parent, token, leaf|
    leaf ? create_class_const(parent, token, &block) : create_module_const(parent, token)
  end
end

.unmock(name) ⇒ Object

Unmock previously mocked class. It doesn’t affect classes created other way then using Imitate.

Parameters:

  • Name (String)

    of the class to be removed.



37
38
39
40
41
# File 'lib/imitate.rb', line 37

def unmock(name)
  process_name(name) do |parent, token|
    self.send((was_mocked?(parent, token) ? :remove_mock : :get_const), parent, token)
  end
end

.unmock_allObject

Unmock all previously mocked classes. It doesn’t affect classes created other way then using Imitate.



47
48
49
50
51
# File 'lib/imitate.rb', line 47

def unmock_all
  MOCKED.slice!(0..-1).each do |mock|
    remove_mock mock[:parent], mock[:name]
  end
end