Search code examples
elixirerlang-otperlang-supervisor

Task causing issues while testing


I currently have a Supervisor that's supervising some Task's. The task is responsible for asynchronously sending an email and updating the database. I'm testing a function which will start these tasks although the task is irrelevant to the test.

When I run the test I see Ecto.StaleEntryError's printed in STDOUT. I believe this is happening because Ecto will delete the record after the test has finished but before the task has run. When it tries to update the record it doesn't exist and therefore an Ecto.StaleEntryError occurs.

As a side note, the test doesn't fail. It only prints a stack trace.

I'm not sure if I should try and prevent the task from executing somehow or if there's another approach.


Solution

  • This is a perfect use case for the explicit contract.

    Make your Supervisor to use different Task implementation, reading from config:

    @task Application.get_env(:my_app, :task_impl)
    

    and execute @task.async instead of Task.async. Also, make config/proc.exs to declare the proper implementation:

    config :my_app, :task_impl, Task
    

    and the test.exs to use TaskStub module instead

    config :my_app, :task_impl, TaskStub
    

    where the TaskStub might look like:

    defmodule TaskStub do
      def async(_), do: :ok
    end
    

    One might also refer to Mox documentation for the inspiration.