UUID working, but tests are failing

Hello, I’m trying to use UUIDs in a Phoenix project. I’ve got it working, but the controller tests (that previously were green) fail with:

** (ArgumentError) Postgrex expected an integer in -2147483648..2147483647 that can be encoded/cast to type "int4", got <<50, 124, 14, 128, 143, 227, 74, 134, 138, 114, 144, 134, 162, 62, 223, 77>>. Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.

I’ve created a dummy app to illustrate the problem, in the first commit we have a simple Post scaffold, tests pass, on the second I convert the ID to UUID, it works, but the tests fail:

Any idea how to fix this? Thanks!

3 Likes

It looks to me like Postgres believes that your UUID column should still be an integer.

If this only happens during testing, make sure you’ve run MIX_ENV=test mix ecto.migrate to ensure that the testing-database is on par with the state of your development database.

4 Likes

Thanks @Qqwy, it only happens during testing, and it keeps happening after MIX_ENV=test mix ecto.migrate.

2 Likes

There it is. Building on @Qqwy’s comment, you need to recreate the test database. So:

MIX_ENV=test mix ecto.drop
MIX_ENV=test mix ecto.create
MIX_ENV=test mix ecto.migrate
mix test

at which point you should run into the other test that fails:

  test "renders page not found when id is nonexistent", %{conn: conn} do
    assert_error_sent 404, fn ->
      get conn, post_path(conn, :show, -1)
    end
  end

which you can fix with get conn, post_path(conn, :show, Ecto.UUID.generate)

As an aside, at the top of test/test_helpers.exs I usually have the following to reset the test database each time.

Mix.Task.run "ecto.drop", ["quiet", "-r", "MyApp.Repo"]
Mix.Task.run "ecto.create", ["quiet", "-r", "MyApp.Repo"]
Mix.Task.run "ecto.migrate", ["-r", "MyApp.Repo"]
11 Likes

Thanks a lot @david!

Makes sense, to make it work in development, I rolled back and re-run the latest migration; in the test environment then I also needed to do this, or recreate the whole database as well.

It works now. Thanks again for your help!

1 Like