Constraint error when attempting to insert struct

Hi, I have an error and can’t understand what I’m doing wrong.

The error:

 ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

     * unique: merchants_slug_index

Here is my table schema:

create table(:merchants) do
  add :name, :string, null: false
  add :slug, :string, null: false

create unique_index(:merchants, [:slug])

I believe the problem is with ex_machina and the fact it doesn’t use changesets, but I’m not entirely sure.
I also think that for some reasons my database doesn’t get cleaned after every test.

Here is the actual test:

setup do
{:ok, service: Owl.ServiceFactory.insert(:service),
admin: Owl.UserFactory.insert(:admin),
merchant: Owl.UserFactory.insert(:merchant)}

  test "GET /macaw/services", %{conn: conn, admin: admin, merchant: merchant} do[admin, merchant],
    fn role ->
      conn = login_as(conn, role) |> get("/macaw/services")
      assert html_response(conn, 200) =~ "Example Service 1"

And the factory:

defmodule Owl.MerchantFactory do
  use ExMachina.Ecto, repo: Owl.Repo

  def merchant_factory do
    %Owl.Merchant{name: "Test Merchant", slug: "test-merchant"}

defmodule Owl.ServiceFactory do
  use ExMachina.Ecto, repo: Owl.Repo

  def service_factory do
    %Owl.Service{name: "Example Service 1", code: "EXAMPLE1",
                 notification_endpoint: "",
                 legacy_notifications: false, merchant: Owl.MerchantFactory.insert(:merchant)}

Changesets really have to be used or you can easily get errors like that. Changesets are what can ‘absorb’ those exceptions and translate them to proper errors on the returned changeset. If it is another library doing that wrong then you should submit an issue to them. Changesets should always be used in my opinion, even in cases where they are optional, they should always still be used. :slight_smile:


I did now, thanks.
I just would like a way to have easy to use factories, what is people using instead of ex_machina??