Ecto.ValidationCase
Ecto.ValidationCase simplifies writing validation tests for Ecto models.
Example
defmodule MyApp.UserTest do
use ExUnit.Case
use Ecto.ValidationCase
alias MyApp.User
test "requires password to be 10 chars long" do
rejects "password", for: [User, :password], message: "too short"
accepts "password123", for: [User, :password]
end
end
The accepts/2
and rejects/2
functions automatically generate a changeset using the specified model's changeset/2
function, and then check the error messages to ensure that each field is validated properly.
Define :model
If you want to save typing, you can specify a model when you use Ecto.ValidationCase
, like this:
use Ecto.ValidationCase, model: MyApp.User
You can then leave the model out of the for:
option, and MyApp.User
will be used by default.
accepts "Daniel Berkompas", for: :name
Of course, if you want to run a validation on a different module, you can still do that:
rejects nil, for: [OtherModel, :name]
To read more, see the documentation of the other functions in this module:
Summary↑
accepts(value, list2) | Verify that a value is accepted by a model's validations |
rejects(value, opts) | Verify that a value is rejected by a model's validations |
Functions
Verify that a value is accepted by a model's validations.
Options
:for
- specifies which field on the model this is for. It can be specified in two forms:for: [Model, :field]
, or justfor: :field
. In the later case, make sure you've specified a model in yourusing
clause.
Examples
accepts "Daniel Berkompas", for: [User, :name]
# Leave out `User` if you specified it as the `:model` in the `using`
# clause:
accepts "Daniel Berkompas", for: :name
Verify that a value is rejected by a model's validations.
Options
:for
- specifies which field on the model this is for. It can be specified in two forms:for: [Model, :field]
, or justfor: :field
. In the later case, make sure you've specified a model in yourusing
clause.:message
- The specific error message that should be returned by the validations.
Examples
# Test that a field is required
rejects nil, for: [User, :name]
# Leave out `User` if you specified it as the `:model` in the `using`
# clause:
rejects nil, for: :name