Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing uniqueness constraints for models
defmodule Example.User do
use Example.Web, :model
schema "users" do
field :email, :string
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email])
|> validate_required([:email])
|> unique_constraint(:email)
end
end
defmodule Example.UserTest do
use Example.ModelCase
alias Example.User
@valid_attrs %{
email: "jdoe@example.com"
}
test "unique constraint on email" do
User.changeset(%User{}, @valid_attrs)
|> Repo.insert!
result =
User.changeset(%User{}, @valid_attrs)
|> Repo.insert
assert {:error, _changeset} = result
end
end
# Make sure to add a unique index to the email field if you don't already have one
defmodule Example.Repo.Migrations.AddUniqueIndexToUsers do
use Ecto.Migration
def change do
create unique_index(:users, [:email])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.