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

Использование detect и include согласовань, чтобы помочь вам здесь:

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

Спасибо. Название реакции может быть nil. почему я получаю эту ошибку? Ошибка/Ошибка: response_reaction_names = response_body ['actions ']. Map {| a | a ['name']} NoMethodError: undefined method 'map 'for nil: NilClass – Micheal

+0

Соответствующая функция patient_allergy_reaction не существует в базе данных. в некоторых случаях будет только больной. Я напечатал json в своем коде выше – Micheal

+1

@ Micheal: обновлен, чтобы отразить структуру JSON. – PinnyM

Смежные вопросы