Guides > Testing
Testing
Controller Serializer Usage
ActiveModelSerializers provides a assert_serializer
method to be used on your controller tests to assert that a specific serializer was used.
class PostsControllerTest < ActionController::TestCase
test "should render post serializer" do
get :index
assert_serializer "PostSerializer"
end
end
See ActiveModelSerializers::Test::Serializer for more examples and documentation.
Serialization against a schema
Dependencies
To use the assert_response_schema
you need to have the json_schema
on your Gemfile. Please add it to your Gemfile and run $ bundle install
.
Minitest test helpers
ActiveModelSerializers provides a assert_response_schema
method to be used on your controller tests to assert the response against a JSON Schema. Let's take a look in an example.
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
render json: @post
end
end
To test the posts#show
response of this controller we need to create a file named test/support/schemas/posts/show.json
. The helper uses a naming convention to locate the file.
This file is a JSON Schema representation of our response.
{
"properties": {
"title" : { "type" : "string" },
"content" : { "type" : "string" }
}
}
With all in place we can go to our test and use the helper.
class PostsControllerTest < ActionController::TestCase
test "should render right response" do
get :index
assert_response_schema
end
end
Load a custom schema
If we need to use another schema, for example when we have a namespaced API that shows the same response, we can pass the path of the schema.
module V1
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
render json: @post
end
end
end
class V1::PostsControllerTest < ActionController::TestCase
test "should render right response" do
get :index
assert_response_schema('posts/show.json')
end
end
Change the schema path
By default all schemas are created at test/support/schemas
. If we are using RSpec for example we can change this to spec/support/schemas
defining the default schema path in an initializer.
ActiveModelSerializers.config.schema_path = 'spec/support/schemas'
Using with the Heroku’s JSON Schema-based tools
To use the test helper with the prmd and committee.
We need to change the schema path to the recommended by prmd:
ActiveModelSerializers.config.schema_path = 'docs/schema/schemata'
We also need to structure our schemata according to Heroku's conventions (e.g. including required metadata and links.
JSON Pointers
If we plan to use JSON Pointers we need to define the id
attribute on the schema. Example:
// attributes.json
{
"id": "file://attributes.json#",
"properties": {
"name" : { "type" : "string" },
"description" : { "type" : "string" }
}
}
// show.json
{
"properties": {
"name": {
"$ref": "file://attributes.json#/properties/name"
},
"description": {
"$ref": "file://attributes.json#/properties/description"
}
}
}