Skip to content

Instantly share code, notes, and snippets.

@clupprich
Last active August 29, 2015 14:24
Show Gist options
  • Save clupprich/59e25627823c8f8cf70e to your computer and use it in GitHub Desktop.
Save clupprich/59e25627823c8f8cf70e to your computer and use it in GitHub Desktop.
JSON Schema matcher
# 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
# 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
# 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