Method: Factory#add_attribute

Defined in:
lib/factory_girl/factory.rb

#add_attribute(name, value = nil, &block) ⇒ Object

Adds an attribute that should be assigned on generated instances for this factory.

This method should be called with either a value or block, but not both. If called with a block, the attribute will be generated “lazily,” whenever an instance is generated. Lazy attribute blocks will not be called if that attribute is overriden for a specific instance.

When defining lazy attributes, an instance of Factory::Proxy will be yielded, allowing associations to be built using the correct build strategy.

Arguments:

  • name: Symbol or String The name of this attribute. This will be assigned using :“#name=” for generated instances.

  • value: Object If no block is given, this value will be used for this attribute.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/factory_girl/factory.rb', line 99

def add_attribute (name, value = nil, &block)
  if block_given?
    if value
      raise AttributeDefinitionError, "Both value and block given"
    else
      attribute = Attribute::Dynamic.new(name, block)
    end
  else
    attribute = Attribute::Static.new(name, value)
  end

  if attribute_defined?(attribute.name)
    raise AttributeDefinitionError, "Attribute already defined: #{name}"
  end

  @attributes << attribute
end