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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With