Last active
August 29, 2015 14:24
-
-
Save clupprich/59e25627823c8f8cf70e to your computer and use it in GitHub Desktop.
JSON Schema matcher
This file contains 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
# spec/support/schema_matcher.rb | |
class Schema | |
@definitions = {} | |
def self.define(name, &block) | |
@definitions[name] = block.call | |
end | |
def self.defined?(name) | |
@definitions.key?(name) | |
end | |
def self.resolve(name) | |
@definitions.fetch(name, {}) | |
end | |
end | |
RSpec::Matchers.define :match_schema do |name| | |
match do |response| | |
schema = Schema.resolve(name) | |
JSON::Validator.validate!(schema, response.body, strict: true) | |
end | |
end |
This file contains 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
# spec/support/schemas/users.rb | |
Schema.define('users') do | |
{ | |
type: :object, | |
properties: { | |
users: { | |
type: :array, | |
items: { | |
type: :object, | |
properties: { | |
name: { | |
type: :string | |
}, | |
id: { | |
type: :number | |
} | |
} | |
} | |
} | |
} | |
} | |
end |
This file contains 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
# spec/request/users_spec.rb | |
require 'spec_helper' | |
describe 'Users' do | |
it 'validates' do | |
response = OpenStruct.new | |
response.body = <<-JSON | |
{ | |
"users": [ | |
{ | |
"name": "John Doe", | |
"id": 1 | |
} | |
] | |
} | |
JSON | |
expect(response).to match_schema('users') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment