2013-03-20 125 views
0

所以我基本上是試圖寫RSpec的測試我的JSON結果: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" 
} 
] 
} 
], 

回答

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 
+0

感謝。反應名稱可以爲零。那是爲什麼我得到這個錯誤?失敗/錯誤:response_reaction_names = response_body ['reactions']。map {| a | a ['name']} NoMethodError: 未定義的方法'map'爲零:NilClass – Micheal 2013-03-20 17:15:10

+0

相應的patient_allergy_reaction在數據庫中不存在。在某些情況下只會出現patient_allergy。我在我的代碼中打印了json,代碼如下 – Micheal 2013-03-20 17:20:20

+1

@Micheal:更新爲反映您的JSON結構。 – PinnyM 2013-03-20 17:33:16