How to test my Ecto Plugin?

A while back I started working on my Hex Package, Ecto.Rut, that provides simple wrapper methods for Ecto models. I’m now trying to write tests for this package, but I have absolutely no idea how to do start Ecto and call a defined schema’s methods during tests. I need to get Ecto running, create/migrate the db before each test and drop it after each test.

I understand that the file test_helper.exs is called beforehand, and this is where I need to put my test model’s schema and run the migrations - but I don’t have the proper direction on how to achieve this.

This is what my test_helper looks like:

I would really appreciate any examples on how I can get my tests to work (getting them to pass is not important right now).

I borrowed a lot of the setup from somewhere else (probably Ecto itself), but maybe give the tests in my project a once over to see how you should start Ecto, run migrations, etc.

1 Like

Thank you @adam12 so much! This was exactly what I needed. I had to make a few changes, but I got it running. This is what my new test_helper looks like:

Code.require_file("test_project.exs", __DIR__)

alias Ecto.Rut.TestProject

# Clean up DB (Do this before every test)
defmodule TestProject.Utils do
  def cleanup do
    Ecto.Migrator.down  TestProject.Repo, 0, TestProject.Migration, log: false
    Ecto.Migrator.up    TestProject.Repo, 0, TestProject.Migration, log: false

# Start Ecto
{:ok, _}    = Ecto.Adapters.Postgres.ensure_all_started(TestProject.Repo, :temporary)
_           = Ecto.Adapters.Postgres.storage_down(TestProject.Repo.config)
:ok         = Ecto.Adapters.Postgres.storage_up(TestProject.Repo.config)
{:ok, _pid} = TestProject.Repo.start_link
1 Like