in factorygirl, any way to refer to the value of field1 when initializing field2?
Asked Answered
K

1

17

Within a factory, how do I refer to the value of one of the other fields in the object being created?

Suppose my model Widget has two fields, nickname and fullname

Inside my factory, I want to use Faker create a different random nickname each time a factory is created. (Finally figured out I have to use sequence(:nickname), otherwise the name is the same for all factories.)

In order to make some of the assertions easier to test for, I want to generate a fullname that is based upon nickname, something like fullname = "Full name for #{nickname}"

FactoryGirl.define do
  factory :widget do 
    sequence(:nickname) { |n| Faker::Lorem.words(2).join(' ') }
    sequence(:fullname) { |n| "Full name for " + ????? }
  end
end

Whatever I put where the ??? goes, I get #<FactoryGirl::Decl... instead of whatever the nickname was set to.

I tried name, name.to_s, name.value... nothing seems to work.

Karalee answered 7/10, 2012 at 1:3 Comment(0)
C
21

Yes. Here's an example from Factory Girl's Getting Started doc:

factory :user do
  first_name "Joe"
  last_name  "Blow"
  email { "#{first_name}.#{last_name}@example.com".downcase }
end

FactoryGirl.create(:user, last_name: "Doe").email
# => "[email protected]"

Also, I usually define my sequences separately, in config/application.rb:

FactoryGirl.define do
  sequence(:random_string) { |s| ('a'..'z').to_a.shuffle[0, 30].join }
end

You might benefit from doing the same. Then you could probably do something like:

FactoryGirl.define do
  factory :widget do 
    nickname generate(:name_faker) # assuming you had defined a :name_faker sequence
    fullname generate("Full name for #{nickname}")
  end
end
Cornellcornelle answered 7/10, 2012 at 1:35 Comment(1)
That was the first thing I tried in my sample code in the question, but instead of #{field1} yielding the field's value, it yields some object #<FactoryGirl::Decl... It might be due having to use sequences.Karalee

© 2022 - 2024 — McMap. All rights reserved.