Class: Cranky::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/cranky/factory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFactory

Returns a new instance of Factory.



6
7
8
9
10
11
12
13
# File 'lib/cranky/factory.rb', line 6

def initialize
  # Factory jobs can be nested, i.e. a factory method can itself invoke another factory method to
  # build a dependent object. In this case jobs the jobs are pushed into a pipeline and executed
  # in a last in first out order. 
  @pipeline = []
  @n = 0
  @errors = []
end

Instance Attribute Details

#debug(*args) ⇒ Object

Can be left in your tests as an alternative to build and to warn if your factory method ever starts producing invalid instances



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/cranky/factory.rb', line 39

def debug(*args)
  item = build(*args) 
  if !item.valid?
    if item.errors.respond_to?("messages")
      errors = item.errors.messages
    else
      errors = item.errors
    end
    raise "Oops, the #{item.class} created by the Factory has the following errors: #{errors}"
  end
  item
end

Instance Method Details

#attributes_for(what, attrs = {}) ⇒ Object



33
34
35
# File 'lib/cranky/factory.rb', line 33

def attributes_for(what, attrs={})
  build(what, attrs.merge(:_return_attributes => true))
end

#build(what, overrides = {}) ⇒ Object



15
16
17
# File 'lib/cranky/factory.rb', line 15

def build(what, overrides={})
  crank_it(what, overrides)
end

#create(what, overrides = {}) ⇒ Object



19
20
21
22
23
# File 'lib/cranky/factory.rb', line 19

def create(what, overrides={})
  item = build(what, overrides)
  item.save
  item
end

#debug!(*args) ⇒ Object

Same thing for create



53
54
55
56
57
# File 'lib/cranky/factory.rb', line 53

def debug!(*args)
  item = debug(*args)
  item.save
  item
end

#resetObject

Reset the factory instance, clear all instance variables



26
27
28
29
30
31
# File 'lib/cranky/factory.rb', line 26

def reset
  self.instance_variables.each do |var|
    instance_variable_set(var, nil)
  end
  initialize
end