Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using factory girl to create a trait of has_many relationship

I'm looking to DRY up my test suite. Trying to create a trait that represents specific values of a has_many relationship on the parent factory. Ideally these values would be created from a separate factory.

I want to do something like this:

factory :room do
  trait :bathroom do 
    type :bathroom
  end
end

factory :house do 
  trait :one_bathroom do 
    association, :rooms, factory: [:room, :bathroom]
  end
end

The above should work if the relationship between house and room was 1 to 1. But House and Room has a One to Many relationship, so a House holds an array of Rooms. Working off this example I would be looking to create a house that had an array of rooms with just one bathroom.

Any ideas?

like image 443
Joshua Book Avatar asked Mar 25 '14 02:03

Joshua Book


1 Answers

To create a one-to-many relationship you could so something like this:

factory :room do
  factory :bathroom do
    type :bathroom
  end
  factory :bedroom do
    type :bedroom
  end
end

factory :house do
  ignore do
    num_bathrooms 0
    num_bedrooms 0
  end

  trait :two_bathrooms do
    num_bathrooms 2
  end

  trait :three_bedrooms do
    num_bedrooms 3
  end

  after(:create) do |house, evaluator|
    create_list(:bathroom, evaluator.num_bathrooms, house: house)
    create_list(:bedroom, evaluator.num_bedrooms, house: house)
  end
end

Check out the last example in the associations section of this link for more details.

like image 167
Leo Avatar answered Nov 01 '22 11:11

Leo