diff options
Diffstat (limited to 'spec/support/matchers/be_valid_json.rb')
-rw-r--r-- | spec/support/matchers/be_valid_json.rb | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/spec/support/matchers/be_valid_json.rb b/spec/support/matchers/be_valid_json.rb new file mode 100644 index 00000000000..f46c35c7198 --- /dev/null +++ b/spec/support/matchers/be_valid_json.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +RSpec::Matchers.define :be_valid_json do + def according_to_schema(schema) + @schema = schema + self + end + + match do |actual| + data = Gitlab::Json.parse(actual) + + if @schema.present? + @validation_errors = JSON::Validator.fully_validate(@schema, data) + @validation_errors.empty? + else + data.present? + end + rescue JSON::ParserError => e + @error = e + false + end + + def failure_message + if @error + "Parse failed with error: #{@error}" + elsif @validation_errors.present? + "Validation failed because #{@validation_errors.join(', and ')}" + else + "Parsing did not return any data" + end + end +end |