Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a local variable within a factory

I have this example

FactoryGirl.define do
  @site = FactoryGirl.create(:my_site)
  factory :user do
    email               { Faker::Internet.email }
    first_name          { Faker::Name.first_name }
    last_name           { Faker::Name.last_name }
    password            { 'TarXlrOPfaokNOzls2U8' }
    active_directory    { '0' }
    companies           { [FactoryGirl.create(:company, site: @site)] }
    sites               { [@site] }
  end
end

Is there a way to achieve this with a let or something...

FactoryGirl.define do
  factory :user do
    email               { Faker::Internet.email }
    first_name          { Faker::Name.first_name }
    last_name           { Faker::Name.last_name }
    password            { 'TarXlrOPfaokNOzls2U8' }
    active_directory    { '0' }
    companies           { [FactoryGirl.create(:company, site: FactoryGirl.create(:my_site))] }
    sites               { [FactoryGirl.create(:my_site)] }

  end
end

This works but it creates two my_site which is a Site object but I need them to be the same...any idea on how to achieve this

like image 651
Matt Elhotiby Avatar asked Jul 06 '12 14:07

Matt Elhotiby


1 Answers

Probably the simplest is to use a local variable:

FactoryGirl.define do
  site = FactoryGirl.create(:my_site)

  factory :user do
    email               { Faker::Internet.email }
    first_name          { Faker::Name.first_name }
    last_name           { Faker::Name.last_name }
    password            { 'TarXlrOPfaokNOzls2U8' }
    active_directory    { '0' }
    companies           { [FactoryGirl.create(:company, site: site)] }
    sites               { [site] }
  end
end
like image 155
tokland Avatar answered Oct 15 '22 20:10

tokland