-
-
Save marcusgadbem/fa1caa41e66d2c9684882172a1b2d172 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