Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Last active October 23, 2023 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nuxlli/5602c51d6727cb14e34cafade3a3a472 to your computer and use it in GitHub Desktop.
Save nuxlli/5602c51d6727cb14e34cafade3a3a472 to your computer and use it in GitHub Desktop.
A mockable Task module for elixir (with mox)
# lib/my_project/task.ex
defmodule MyProject.Task do
@moduledoc """
TODO: run async task on tests will not work, with unpredictable side effects
"""
@adapter Keyword.get(
Application.compile_env(:my_project, __MODULE__, []),
:adapter,
Task
)
@callback async(term()) :: term()
defdelegate async(func), to: @adapter
end
# configs/test.exs
config :my_project, MyProject.Task
adapter: MyProject.Task.MockAdapter
# tests/support/mocks.ex
Mox.defmock(MyProject.Task.MockAdapter, for: MyProject.Task)
# test/lib/my_project/task_test.exs
test "spawn a task" do
MyProject.Task.MockAdapter |> expect(:async, 1, fn fun -> fun.() end)
assert capture_log(fn ->
MyProject.Task.async(fn ->
Logger.error("Houston, we have a problem")
end)
end) =~ "Houston, we have a problem"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment