Created
March 11, 2019 09:34
-
-
Save benoittgt/46f7a33ced8ab40b9db61d6627ff2c73 to your computer and use it in GitHub Desktop.
JSONAPI data size matcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
RSpec::Matchers.define :have_data_count_of do |expected| | |
match do |actual| | |
if actual.is_a?(Hash) | |
@json_api_payload = actual | |
elsif actual.is_a?(String) | |
@json_api_payload = JSON.parse(actual) | |
else | |
@invalid_payload_type_error = 'Please provide a Hash or JSON string' | |
return false | |
end | |
unless data_payload | |
@missing_data_key_error = "Can't find \"data\" key in JSON API payload" | |
return false | |
end | |
unless data_payload.is_a?(Array) | |
@invalid_data_type = '"data" is not an array' | |
return false | |
end | |
data_payload.size == expected | |
end | |
failure_message do |_actual| | |
if validity_error | |
"Invalid payload: #{validity_error}" | |
else | |
"expected that JSONAPI \"data\" contains #{expected} elements but it contains #{@data_payload.size}" | |
end | |
end | |
description do | |
"expect that JSONAPI data contains #{expected} elements" | |
end | |
def validity_error | |
@invalid_payload_type_error || @missing_data_key_error || @invalid_data_type | |
end | |
def data_payload | |
@data_payload ||= @json_api_payload[:data] || @json_api_payload['data'] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment