Using factory girl to create a trait of has_many relationship
Asked Answered
M

1

5

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?

Misreport answered 25/3, 2014 at 2:5 Comment(0)
P
8

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.

Peti answered 28/3, 2014 at 3:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.