Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 452
jpw Avatar asked Oct 07 '12 01:10

jpw


1 Answers

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
like image 174
Jason Swett Avatar answered Sep 17 '22 23:09

Jason Swett