Search code examples
elixirphoenix-frameworkecto

Testing elixir controller which works on a schema with association


I have a controller that works on schema called forms. This schema has a belongs_to association with the user.
When I let the tests run I now get the error that the data can't be saved to the database since the user with the id in the fixture doesn't exist. Now I am thinking on how to solve this. I could write a user to the database and make sure there is always a valid user, or mock the user, I guess.
What would be the "canonical" way to do so? If I should create the user in the database, I would have to do this for (nearly) every other schema as well so how can a dry this up?


Solution

  • In addition to previous answers, it is better not to use business logic functions to fill test DB, because those functions can contain bugs too.

    Most common solutions are either insert directly into the DB: https://blog.danielberkompas.com/2015/07/16/fixtures-for-ecto/,
    or use factories: https://github.com/thoughtbot/ex_machina, which make all the insertions behind the scene.

    And regardless of an option you choose, all tests are wrapped in transactions (with Ecto.Adapters.SQL.Sandbox) and DB would clear up after each test.