【问题标题】:testing models with builds or matcher in factory girl在工厂女孩中使用构建或匹配器测试模型
【发布时间】:2013-03-23 18:06:32
【问题描述】:

我有以下工厂用于处理 Patient_allergies

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) 匹配器之类的。

如果我能理解用工厂女孩测试我的模型,那将非常有帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot rspec-rails


    【解决方案1】:

    以上工作正常,但似乎没有增加多少价值

    同意。您的模型规范应该测试您编写的方法,而不是测试 Rails 的行为。

    如果你想测试你的关联,你可以查看shoulda-matchers,它有针对 Rails 模型的标准测试。

    【讨论】:

    • 有没有一种方法可以测试我上面的代码而不需要。在这种情况下,我不想使用外部 gem。
    • 查看 should_matchers (github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/…) 的代码。请注意,它不是创建和保存模型实例——它只是测试您是否正确设置了模型,而不是 ActiveRecord 代码本身是否有效。 Rails 对此有自己的测试。
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多