malcoauri
malcoauri

Reputation: 12209

How to pass argument for FactoryGirl method

There is the following code for creating objects:

FactoryGirl.define do

  factory :user do
    name    'Some name'
    phone   '89277777777'
    address 'Some address'
  end

  factory :order do
    title   'Some title'
  end
end

User model has got has_many :orders association, and is it possible to pass user factory to order factory?

Thanks in advance.

Upvotes: 1

Views: 98

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176562

Yes, the solution is as simple as using the association method

factory :order do
  title   'Some title'
  association :user
end

that can be shortened to

factory :order do
  title   'Some title'
  user
end

A word of warning. This approach tends to make your application very slow as long as the complexity of your models will increase.

In fact, if you have a purchase associated to an order associated to an user, etc, then creating a Purchase will create on cascade all the associated records even if you don't need them. Your tests will become slower over the time.

I suggest you to use the traits to compose your associations only when required.

factory :order do
  title   'Some title'

  trait :with_user do
    user
  end
end

FactoryGirl.create(:order, :with_user)

I normally also use :with_fake_user when I need the user id to be present for validation, but I'm testing something that doesn't require to access the user.

factory :order do
  title   'Some title'

  trait :with_user do
    user
  end
  trait :with_fake_user do
    user_id 0
  end
end

FactoryGirl.create(:order, :with_user)
FactoryGirl.create(:order, :with_fake_user)

Upvotes: 0

veritas1
veritas1

Reputation: 9190

Yes, as follows:

FactoryGirl.define do

  factory :user do
    name    'Some name'
    phone   '89277777777'
    address 'Some address'
  end

  factory :order do
    user
    title   'Some title'
  end
end

In your specs:

FactoryGirl.create(:order)

will create both an order object and an associated user object.

more information on FactoryGirl with Rails - https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Upvotes: 1

Related Questions