Class: Factory

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

Overview

FactoryGirl replacement (because original FactoryGirl is bloated, and even more - it depends on activesupport, and this makes it too unconvinient to use in non-Rails environments).

Defined Under Namespace

Classes: Builder

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFactory

Returns a new instance of Factory.



38
39
40
# File 'lib/rspec_ext/factory.rb', line 38

def initialize
  @registry, @counters = {}, Hash.new(0)
end

Instance Attribute Details

#countersObject (readonly)

Returns the value of attribute counters.



36
37
38
# File 'lib/rspec_ext/factory.rb', line 36

def counters
  @counters
end

#registryObject (readonly)

Returns the value of attribute registry.



36
37
38
# File 'lib/rspec_ext/factory.rb', line 36

def registry
  @registry
end

Instance Method Details

#auto(*args, &block) ⇒ Object



72
73
74
75
# File 'lib/rspec_ext/factory.rb', line 72

def auto *args, &block
  method = creation_method || raise("creation method not defined!")
  send method, *args, &block
end

#build(name, attributes = {}, &block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rspec_ext/factory.rb', line 47

def build name, attributes = {}, &block
  old = creation_method
  begin
    self.creation_method ||= :build

    builder = registry[name] || raise("no definition for :#{name}!")
    builder.build attributes, &block
  ensure
    self.creation_method = old
  end
end

#create(name, attributes = {}, &block) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rspec_ext/factory.rb', line 59

def create name, attributes = {}, &block
  old = creation_method
  begin
    self.creation_method ||= :create

    o = build name, attributes, &block
    o.respond_to?(:save!) ? o.save! : o.save
    o
  ensure
    self.creation_method = old
  end
end

#define(name, options = {}, &initializer) ⇒ Object



42
43
44
45
# File 'lib/rspec_ext/factory.rb', line 42

def define name, options = {}, &initializer
  raise "definition of :#{name} already exist!" if registry.include? name
  registry[name] = Builder.new(name, options, &initializer)
end

#next(name = :general) ⇒ Object



77
78
79
80
81
# File 'lib/rspec_ext/factory.rb', line 77

def next name = :general
  v = counters[name]
  counters[name] += 1
  v
end