I'm trying to test uniqueness in my database and I'm having a little trouble. I ran this migration:
def change do
create table(:signups) do
add :name, :string
add :email, :string
timestamps()
end
create unique_index(:signups, [:email])
end
have this changeset def in my model:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :email])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> update_change(:email, &String.downcase/1)
|> unique_constraint(:email)
end
and the test that's failing is:
test "duplicate email changeset is invalid" do
%Signup{}
|> Signup.changeset(@valid_attrs)
|> Repo.insert!
user2 = %Signup{}
|> Signup.changeset(@valid_attrs)
assert {:error, _changeset} = Repo.insert(user2)
end
The second insert seems to go through even though it shouldn't. The exact error returned is:
1) test duplicate email changeset is invalid (EventSignup.SignupTest)
test/models/signup_test.exs:24
match (=) failed
code: {:error, _changeset} = Repo.insert(user2)
rhs: {:ok,
%EventSignup.Signup{__meta__: #Ecto.Schema.Metadata<:loaded, "signups">,
email: "[email protected]", id: 41,
inserted_at: #Ecto.DateTime<2016-09-11 19:35:40>,
name: "some content",
updated_at: #Ecto.DateTime<2016-09-11 19:35:40>}}
stacktrace:
test/models/signup_test.exs:31: (test)
Does anyone see what I'm missing here? If I manually insert two of the same records through iex the second insert will fail but during the test it's passing.
MIX_ENV=test mix do ecto.drop, ecto.create, ecto.migrate) and then running the tests. - Dogbert