Cleaning up after tests (on_exit)

almirsarajcic

almirsarajcic

Created yesterday

When your tests create files, database records, or other side effects, you need to clean them up regardless of whether the test passes or fails.

Database changes are already handled by Ecto’s sandbox.

But if you work with files, you need to clean them up yourself.
Use ExUnit’s on_exit/1 callback:

test "updates user's avatar", %{user: user} do
  upload_path = "/tmp/avatar_#{System.unique_integer()}.png"

  on_exit(fn -> File.rm(upload_path) end)

  File.write!(upload_path, "fake PNG data")

  {:ok, updated_user} = Accounts.update_avatar(user, upload_path)

  assert updated_user.avatar_url
  assert File.exists?(upload_path) # true
end

The cleanup function runs after the test completes, even if it crashes or fails an assertion, preventing flaky tests in future runs.