Last active
October 23, 2023 15:48
-
-
Save nuxlli/5602c51d6727cb14e34cafade3a3a472 to your computer and use it in GitHub Desktop.
A mockable Task module for elixir (with mox)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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