Module: Gonzales::FactoryGirl::DefinitionProxy

Defined in:
lib/gonzales/factory_girl/definition_proxy.rb

Overview

Gonzales::FactoryGirl::DefinitionProxy

Extends FactoryGirl with a new extension

Instance Method Summary collapse

Instance Method Details

#speedy(attribute_or_factory, *args) ⇒ Object

Define an association in a factory. Supports belongs_to and has_and_belongs_to_many associations

speedy will assign the association in the following order:

#. If you have specified the association then insgtantiating creating or building the factory,
   it will use that association
#. If the association exists in the database, it will assign that.
#. Lastly, when none of the above, it will create the factory.

Arguments

* association_name - the name of the association
* factory_name - the name of the factory (if the factory has the same name as the association, this parameter is optional)
* options - a hash to be passed to FactoryGirl when creating the record using factory

Examples

FactoryGirl.define do
  factory :organization do
    name "Looney tunes"
    speedy :contact                                      # association to contact (belongs_to :contact), 
           # same as +association :contact+
    speedy :addresses, :street_address, :postal_address  # association to addresses (has_many_and_belongs_to_many :addresses)
           # same as +addresses { |org| [org.association(:street_address), org.association(:postal_address)] }+
  end
end


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/gonzales/factory_girl/definition_proxy.rb', line 58

def speedy(attribute_or_factory, *args)
  attribute = attribute_or_factory
  options = args.extract_options!
  after_build do |r|
    begin
      if r.class.reflect_on_association(attribute).macro.to_s.include? 'has_and_belongs_to_many'
        if r.send(attribute).size == 0
          factory_names = args.size > 0 ? args : [attribute]
          r.send("#{attribute}=",
            factory_names.collect { |factory_name| Collection.entity(factory_name) || Adapter.create(factory_name, options) }) 
        end
      elsif !r.send(attribute)
        factory_name = args.first || attribute
        r.send("#{attribute}=", Collection.entity(factory_name) || Adapter.create(factory_name, options))
      end
    rescue NoMethodError => e
      if e.message.include? 'macro'
        raise UndefinedAssociation.new("association #{attribute} is undefined")
      else
        raise e
      end
    end
  end
end