Validate the JSON returned by your Rails JSON APIs
Add this line to your application's Gemfile:
gem 'json-matchers', require: false
And then execute:
$ bundle
Or install it yourself as:
$ gem install json-matchers
Inspired by Validating JSON Schemas with an RSpec Matcher
First, include it in your spec_helper
:
# spec/spec_helper.rb
require "json/matchers"
Define your JSON Schema in the schema directory:
# spec/support/api/schemas/posts.json
{
"type": "object",
"required": ["posts"],
"properties": {
"type": "object",
"required": ["id", "title", "body"],
"properties": {
"id": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "string" }
}
}
}
Then, validate your response against your schema with match_response_schema
# spec/requests/posts_spec.rb
describe "GET /posts" do
it "returns Posts" do
get posts_path, format: :json
expect(response.status).to eq 200
expect(response).to match_response_schema("posts")
end
end
To DRY up your schema definitions, use JSON schema's $ref
.
First, declare the singular version of your schema.
# spec/support/api/schemas/post.json
{
"type": "object",
"required": ["id", "title", "body"],
"properties": {
"id": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "string" }
}
}
Then, when you declare your collection schema, reference your singular schemas.
# spec/support/api/schemas/posts.json
{
"type": "object",
"required": ["posts"],
"properties": {
"posts": {
"type": "array",
"items": { "$ref": "post.json" }
}
}
}
NOTE: $ref
resolves paths relative to the schema in question.
In this case "post.json"
will be resolved relative to
"spec/support/api/schemas"
.
To learn more about $ref
, check out Understanding JSON Schema Structuring
By default, the schema directory is spec/support/api/schemas
.
This can be configured via JSON::Matchers.schema_root
.
# spec/support/json-matchers.rb
JSON::Matchers.schema_root = "docs/api/schemas"
- Fork it ( https://github.com/[my-github-username]/json-matchers/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request