Method: FactoryBot::DefinitionProxy#association

Defined in:
lib/factory_bot/definition_proxy.rb

#association(name, *options) ⇒ Object

Adds an attribute that builds an association. The associated instance will be built using the same build strategy as the parent instance.

Example:

factory :user do
  name 'Joey'
end

factory :post do
  association :author, factory: :user
end

Arguments:

  • name: Symbol The name of this attribute.

  • options: Hash

Options:

  • factory: Symbol or String

    The name of the factory to use when building the associated instance.
    If no name is given, the name of the attribute is assumed to be the
    name of the factory. For example, a "user" association will by
    default use the "user" factory.
    


155
156
157
158
159
160
161
162
163
164
165
# File 'lib/factory_bot/definition_proxy.rb', line 155

def association(name, *options)
  if block_given?
    raise AssociationDefinitionError.new(
      "Unexpected block passed to '#{name}' association " \
      "in '#{@definition.name}' factory"
    )
  else
    declaration = Declaration::Association.new(name, *options)
    @definition.declare_attribute(declaration)
  end
end