Skip to content

Instantly share code, notes, and snippets.

@marcusgadbem
Forked from nuxlli/mokable_task.ex
Created October 23, 2023 15:48
Show Gist options
  • Save marcusgadbem/fa1caa41e66d2c9684882172a1b2d172 to your computer and use it in GitHub Desktop.
Save marcusgadbem/fa1caa41e66d2c9684882172a1b2d172 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