Micheal
Micheal

Reputation: 2322

rspec for testing json results

So I am basically trying to write rspec to test my json results:

 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

My tables above are patient_allergies and patient_allergy_reactions.

The above tests work fine. But the problem is I am comparing by index.

If the order of the json changes, the test would fail. Is there a better way to write tests for this? my json looks like this:

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

Upvotes: 0

Views: 430

Answers (1)

PinnyM
PinnyM

Reputation: 35533

Use detect and the include matcher to help you out here:

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

Upvotes: 1

Related Questions