0
votes

I'm new to Elixir, so I'm having trouble nailing this down. If you want to see additional files let me know - I don't know yet what's important or not to include.

I have an "Account" object that has many "User" objects. I'm trying to update a user with the associated account using Ecto.Changset.cast_assoc. It works fine from iEx, but in the unit test, I get:

(Ecto.ConstraintError) constraint error when attempting to update struct:
* users_account_id_fkey (foreign_key_constraint)

Now, I know this has something to do with the Ecto Sandbox, but I can't figure out how to write the test so that it works. I could just move on and not write this test, but I want to understand how to make it work for the future.

In my project, I have a Test Helper that looks like so (just setting up third party apps):

ExUnit.start()

{:ok, _} = Application.ensure_all_started(:wallaby)
{:ok, _} = Application.ensure_all_started(:ex_machina)
Faker.start()

Application.put_env(:wallaby, :base_url, BondiWeb.Endpoint.url())

I also have standard channel_case, conn_case, data_case and I haven't changed those. Finally, my test.exs is pointing to the sandbox adapter:

pool: Ecto.Adapters.SQL.Sandbox

I've tried several variations of the different sandbox modes (:auto, :manual, :shared) but can't seem to figure out how to setup this test so that both records can be inserted and the test passes.

I suspect it has something to do with my uses ExMachina to manage my fixtures, and that I'm "doing it wrong". But I also tried to create the user directly, without using ExMachina and that didn't seem to work either.

How do I write a test that can make multiple associated saves to the sandbox, and have them remain until the end of the test?

1
Just to be sure, can you try to run mix ecto.reset, both with and without MIX_ENV=test? When you run iex, you are by default in the dev mix env, while tests run in the test env, both using a different database. This might explain a difference in behaviour as well. - sabiwara
the error most likely tells that you are trying to update to a foreign key that doesn't exist - Daniel
Like @sabiwara said: make sure you run MIX_ENV=test mix ecto.migrate (or do the full drop, create, migrate reset) to ensure that your test database is in the shape that your tests expect it to be in. - Everett

1 Answers

0
votes

Thanks to everyone who commented. It does appear that it was related to the test DB not being dropped / recreated. I swear I did that, but I guess not!

For the record I did:

MIX_ENV=test mix ecto.reset

reran the test, and it worked.