Search code examples
testingelixirphoenix-frameworkecto

Why am I getting this foreign key error in my phoenix tests?


I've got the following test in Phoenix:

test "list_orders/0 returns all orders" do
  {:ok, user} = %User{}
                |> User.changeset(@user_attrs)
                |> Repo.insert()

  changeset = %Order{}
              |> Order.changeset(@valid_attrs)
              |> Ecto.Changeset.put_change(:user_id, user.id)

  {:ok, order} = Repo.insert(changeset)

  assert MWS.list_orders() == [order]
end

Which is failing to insert changeset into the Repo because user_id is failing a foreign key constraint. But I'm using the user.id that's returned from the user successfully being inserted into the database?

Any idea what I'm doing wrong here?

Thanks!


Solution

  • As Kalvin Hom points out, you need to look at the schema/migrations to understand this:

    defmodule BarronWatchCompany.Repo.Migrations.AddUsersToOrders do
      use Ecto.Migration
    
      def change do
    
        alter table(:orders) do
          add :user_id, references(:orders, on_delete: :nothing)
        end
    
        create index(:orders, [:user_id])
      end
    end
    

    The problem is that I was referenceing orders and not users. I've migrated the database:

    defmodule BarronWatchCompany.Repo.Migrations.AddUserToOrders do
      use Ecto.Migration
    
      def up do
        drop constraint(:orders, "orders_user_id_fkey")
    
        alter table(:orders) do
          modify :user_id, references(:users, on_delete: :nothing), null: false
        end
      end
    end
    

    And I can now create orders :)