0

所以我基本上是在尝试编写 rspec 来测试我的 json 结果:

 patient_allergies = patient.patient_allergies
  expect(response_body['allergies'].size).to eq(patient_allergies.size)

  patient_allergies.each_with_index do |allergy, index|
    expect(response_body['allergies'][index]['name']).to eq(allergy.name)
    allergy.patient_allergy_reactions.each_with_index do |reaction, index|
      expect(response_body['reactions'][index]['name']).to eq(reaction.name)
    end
  end

我上面的表格是 patient_allergies 和 patient_allergy_reactions。

上述测试工作正常。但问题是我正在按索引进行比较。

如果 json 的顺序发生变化,测试将失败。有没有更好的方法来为此编写测试?我的 json 看起来像这样:

"allergies": [
{
"name": "Allergy1",
"reactions": [
]
},
{
"name": "Allergy2",
"reactions": [
{
"name": "Reaction1",
"severity": "Medium"
}
]
}
],
4

1 回答 1

1

在这里使用detectinclude匹配器来帮助你:

patient_allergies = patient.patient_allergies
response_allergies = response['allergies'] || []

expect(response_allergies.size).to eq(patient_allergies.size)
patient_allergies.each |allergy| do
  response_allergy = response_allergies.detect{|a| a['name'] == allergy.name}
  expect(response_allergy).to_not be_nil
  patient_reactions = allergy.patient_allergy_reactions
  response_reactions = (response_allergy['reactions'] || []).map{|r| r['name']}
  expect(response_reactions.size).to eq(patient_reactions.size)
  expect(response_reactions).to include(*patient_reactions.map(&:name))
end
于 2013-03-20T17:02:02.337 回答