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
endSee ActiveModelSerializers::Test::Serializer for more examples and documentation.
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.
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
endTo 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
endIf 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
endclass V1::PostsControllerTest < ActionController::TestCase
test "should render right response" do
get :index
assert_response_schema('posts/show.json')
end
endBy 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'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.
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"
}
}
}