2013-03-20 87 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