Reputation: 15259
Given these Rails models:
class Human
has_many :pets
has_many :vet_visits
end
class Pet
belongs_to :human
has_many :vet_visits
end
class VetVisit
belongs_to :human
belongs_to :pet
end
I need an rspec factory to make a VetVisit. But:
FactoryGirl.define do
factory :vet_visit, class: 'VetVisit' do
association :human, factory: :human
association :pet, factory: :pet
end
factory :pet, class: 'Pet' do
association :human, factory: :human
end
factory :human, class: 'Human' do
after(:create) do | human |
create :pet, human: human
end
end
end
results in a vet_visit with a human and a pet which are not each other's respective pet/human.
How do I make a factory which creates a vet_visit which has a pet with a human which is the same human as referenced by the vet_visit?
To clear any doubt, I am not in fact making a vetinary system, this is an abstract example from a more complex system, removing the human and doing vet_visit.pet.human in the code is not suitable
Upvotes: 1
Views: 1112
Reputation: 153
I think you need to use inverse_of
relationships in order for this to work.
When you create a human, a pet is created. That pet belongs to the human, but the human doesn't know about the pet.
Have a look here: http://guides.rubyonrails.org/association_basics.html#bi-directional-associations
Upvotes: 0
Reputation: 402
If you need a vet visit that refers to a specific pet and human then build it within your spec file.
let(:vet_visit) { FactoryGirl.create(:vet_visit, human: human, pet: pet) }
This presumes you've already created a human and pet within your spec file.
Upvotes: 2