summaryrefslogtreecommitdiff
path: root/spec/support/api/schema_matcher.rb
blob: 4cf34d43117b29c854a49893d1dd3d06e206a4b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
module SchemaPath
  def self.expand(schema, dir = nil)
    if Gitlab.ee? && dir.nil?
      ee_path = expand(schema, 'ee')

      return ee_path if File.exist?(ee_path)
    end

    Rails.root.join(dir.to_s, 'spec', "fixtures/api/schemas/#{schema}.json").to_s
  end
end

RSpec::Matchers.define :match_response_schema do |schema, dir: nil, **options|
  match do |response|
    @errors = JSON::Validator.fully_validate(
      SchemaPath.expand(schema, dir), response.body, options)

    @errors.empty?
  end

  failure_message do |response|
    "didn't match the schema defined by #{SchemaPath.expand(schema, dir)}" \
    " The validation errors were:\n#{@errors.join("\n")}"
  end
end

RSpec::Matchers.define :match_schema do |schema, dir: nil, **options|
  match do |data|
    @errors = JSON::Validator.fully_validate(
      SchemaPath.expand(schema, dir), data, options)

    @errors.empty?
  end

  failure_message do |response|
    "didn't match the schema defined by #{SchemaPath.expand(schema, dir)}" \
    " The validation errors were:\n#{@errors.join("\n")}"
  end
end