RSpec how to very JSON response with params hash
Option 1:
The params hash will be defined as the below
let!(:valid_params) { { event_type: 'income', event_date: Time.now, value: 1000, note: 'update record 2' } }
Then when performing an update (PUT action) we will receive the response in JSON
So we can compare every element of the hash with JSON object
expect(JSON.parse(response.body)["value"]).to eq(valid_params[:value])
expect(JSON.parse(response.body)["note"]).to eq(valid_params[:note])
Option 2:
Another way is to use a custom matcher
Define a matcher as the following:
RSpec::Matchers.define :have_updated_attributes do |expected_attributes|
match do |actual_json|
return false unless actual_json
expected_attributes.all? do |key, value|
if value && (value.is_a?(Time) || value.is_a?(DateTime))
actual_json[key.to_s][0..18] == value.strftime("%Y-%m-%dT%H:%M:%S")
else
actual_json[key.to_s] == value
end
end
end
failure_message do |actual_json|
"expected is: #{expected_attributes} but actual is: #{actual_json}"
end
end
Then check everything in one command
expect(JSON.parse(response.body)).to have_updated_attributes(valid_params)