0

私は患者のアレルギーのために次の工場を持っています

FactoryGirl.define do
  factory :patient_allergy do
    patient
    name 'Peanuts'
  end
end

Patient_allergy_reactions の次のファクトリ

FactoryGirl.define do
  factory :patient_allergy_reaction do
    patient_allergy
    name 'Fever'
    severity 'High'
  end
end

Patient_allergy のモデルは次のようになります。

class PatientAllergy < ActiveRecord::Base
  belongs_to :patient
  has_many :patient_allergy_reactions
end

Patient_allergy_reaction のモデルは次のようになります。

class PatientAllergyReaction < ActiveRecord::Base
  belongs_to :patient_allergy
end

私のモデルテストは次のようになります。

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

上記は正常に機能しますが、あまり価値がないようです。上記のテストにビルドと特性を使用する方法を見つけようとしています。そうでなければ、expect(patient).to have_many(:patient_allergies) マッチャーなどを使用する方法はありますか。

factory girl でモデルをテストすることを理解できれば、本当に助かります。

4

1 に答える 1

1

上記は正常に機能しますが、あまり価値がないようです

同意した。モデル仕様では、Rails の動作をテストするのではなく、作成したメソッドをテストする必要があります。

関連付けをテストしたい場合は、Rails モデルの標準テストが含まれているshoulda-matchersを確認できます。

于 2013-03-23T23:00:20.637 に答える