Packages

Custom ESpec matchers to ease testing of JSON API endpoints.

Current section

Files

Jump to
espec_json_api_matchers lib espec_json_api_matchers.ex
Raw

lib/espec_json_api_matchers.ex

defmodule ESpecJSONAPIMatchers do
@moduledoc """
Import this module in your spec module to make custom matchers available to your tests.
```
defmodule MyAppSpec do
import ESpecJSONAPIMatchers
end
```
Once that's done, you can use any of the provided matchers as documented in the functions below.
"""
alias ESpecJSONAPIMatchers.{ConformToSchema, HaveRelationshipTo, IncludeRelated, MatchIgnoring}
@doc """
Ensures a resource object node contains the expected set of `attributes`.
Any missing or extraneous attributes cause the test to fail.
```
expect(article_node) |> to(conform_to_schema [:title, :body, :published_at])
```
"""
def conform_to_schema(schema), do: {ConformToSchema, schema}
@doc """
Ensures a resource object node's `relationships` contain a key for the specified entity type.
```
expect(article_node) |> to(have_relationship_to :comments)
```
"""
def have_relationship_to(entity), do: {HaveRelationshipTo, entity}
@doc """
Ensures a top-level node has at least one `included` object of the specified entity type.
```
expect(top_level_node) |> to(include_related :comments)
```
"""
def include_related(entity), do: {IncludeRelated, entity}
@doc """
Ensures a JSON response (or part of a JSON response) matches the expected `reference_response`.
The reference response may include fields with an `:ignored` value, in which case the matcher will
ensure the field is defined but ignore its value when comparing. This is useful for auto-generated
fields like primary keys, creation dates, etc.
```
expect(node) |> to(match_ignoring %{id: :ignored, name: "Michael Scott"})
```
"""
def match_ignoring(reference_response), do: {MatchIgnoring, reference_response}
end