I have the following factory for patient_allergies
FactoryGirl.define do
factory :patient_allergy do
patient
name 'Peanuts'
end
end
The following factory for patient_allergy_reactions
FactoryGirl.define do
factory :patient_allergy_reaction do
patient_allergy
name 'Fever'
severity 'High'
end
end
The model for patient_allergy looks like this:
class PatientAllergy < ActiveRecord::Base
belongs_to :patient
has_many :patient_allergy_reactions
end
the model for patient_allergy_reaction looks like this:
class PatientAllergyReaction < ActiveRecord::Base
belongs_to :patient_allergy
end
My model tests look this:
it 'returns correct allergies with reactions' do
#create an allergy
allergy_name = 'Peanuts'
patient_allergy = create(:patient_allergy, name: allergy_name, patient: patient)
#create a allergy reaction
reaction_name = 'Fever'
reaction_severity = 'Low'
allergy_reaction = create(:patient_allergy_reaction, name: reaction_name, severity: reaction_severity, patient_allergy: patient_allergy)
expect(patient.patient_allergies.size).to eq(1)
expect(patient.patient_allergies[0]).to eq(patient_allergy)
expect(patient.patient_allergies[0].patient_allergy_reactions[0]).to eq(allergy_reaction)
end
The above works fine but doesnt seem to add much value. I am trying to figure out a way to use build and traits for the above test. Else, is there a way to use the expect(patient).to have_many(:patient_allergies) matcher or something.
It would be really helpful if i could understand testing my models with factory girl.
The above works fine but doesnt seem to add much value
Agreed. Your model specs should test methods that you write, instead of testing the behavior of Rails.
If you want to test your associations, you can check out shoulda-matchers, which has standard tests for Rails models.