Last active
December 8, 2016 14:34
-
-
Save chalmagean/d3e18133deb5b47fd999b4f31ef5f21f to your computer and use it in GitHub Desktop.
Testing uniqueness constraints for models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "[email protected]" | |
} | |
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