Reputation: 11030
I have the following seed file that creates specific types of animals that need to be tested:
animal_seeder.rb
# frozen_string_literal: true
animal1 = create(:animal, name:"id0_12", type:"fish, score: 2 ...)
animal2 = create(:animal, name:"id0_123",type:"dog", score: 121 ...)
animal3 = create(:animal, name:"id0_997",type:"cat", score: 5 ...)
The problem I'm running into right now is that I have 2 others seeders called store_seeder.rb and food seeder that relies on using the animal variables created in the animal_seeder.
eg.
create(
:animal_store,
timestamp: DateTime.now,
version: 3,
targets: {
"food": {
food.id=>{
"animals": {
animal1.id =>{
score:1231,
present: true,
.....
}
We are looking to test specific use cases so I can't randomly create the variables for the animal variable. Is there a way I can create the animals and use them as a reference across other seeds?
Upvotes: 0
Views: 196
Reputation: 164739
First, get rid of fixtures. As you're discovering, they're hard to maintain.
Instead, create the animals as needed for your particular tests and pass them to the store.
let(:animals) {
create_list(:animal, 3)
}
let(:animal_store) {
create(:animal_store, animals: animals)
}
Now you know that animal_store
contains animals
.
Adding those specific animals to the animal_store
does not appear to be straight forward. You have to build whole Hash structure and Food objects... don't bother the test author with the details, instead pass the animals as a transient attribute and do the work in the factory.
factory :animal_store do
# Give them sensible defaults.
transient do
animals { create_list(:animal, num_target_animals) }
num_animals { 3 }
foods { create_list(:food, num_foods) }
num_foods { 3 }
end
timestamp { DateTime.now }
# targets is complex enough that it benefits from its own factory.
# Pass the supplied animals and foods through.
targets factory: :animal_store_targets, animals: animals, foods: foods
end
factory :animal_store_targets, class: Hash do
transient do
animals { create_list(:animal, num_target_animals) }
num_animals { 3 }
foods { create_list(:food, num_foods) }
num_foods { 3 }
end
targets do
# I'll leave building the targets Hash from animals and foods to you.
end
# Cheap trick to make a Hash with symbol keys.
initialize_with do
attributes
end
end
Upvotes: 2