We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Multi-process collaboration in Mox
Deankinyua
Created
Mox enforces process-based verification, meaning only the process that defines expectations is allowed to call the mock by default. This can prove problematic when you are executing code that runs in a different process for example inside a Task:
def process_users(user_ids) do
Task.async(fn ->
result = MyApp.Accounts.process_users_details(user_ids)
end)
end
Here process_users/1 executes on a different process. When defining tests:
expect(MockAccounts, :process_users_details, fn _user_ids ->
{:ok, user_details}
end)
assert {:ok, user_details} == MyApp.Accounts.process_users(user_ids)
This will not work because we are using expectations defined in a different process than the one calling the actual function. To fix this we need to tell Mox to use global mode so that mocks can be consumed by any process (not necessarily the one that authored them). To do this however the ExUnit case must be set to async: false.
use MyApp.DataCase, async: false
then we can immediately set the mode depending on the context ; when async: true, Mox will use :set_mox_private but we want to set global mode so:
use MyApp.DataCase, async: false
setup :set_mox_from_context
Copy link
copied to clipboard