Carl Edwards Carl Edwards - 5 months ago 14
Ruby Question

Using the same value for two attributes in FactoryGirl

I'm setting up an

Artist
model that has
name
and
birth_name
attributes. In some cases, an artist's stage name is synonomous with their real name, vice-versa. What I'd like to do in my factory is use the
birth_name
(created using Faker) as the
name
attribute. I tried simply referencing as so:

FactoryGirl.define do
factory :artist do
name { birth_name }
birth_name { Faker::Name.name }
end
end


but get this error:

ArgumentError: Factory not registered: birth_name


What's the best way to get this to work?

Answer

You can use Transient Attributes for this. Documentation says about this:

Static and dynamic attributes can be created as transient attributes. Transient attributes will be ignored within attributes_for and won't be set on the model, even if the attribute exists or you attempt to override it...

FactoryGirl.define do
  factory :artist do
    transient do
      birth_name { Faker::Name.name }
    end

    name { birth_name }
  end
end