diff --git a/lib/tesla/mock.ex b/lib/tesla/mock.ex index 3dc7bf76..9e59ce72 100644 --- a/lib/tesla/mock.ex +++ b/lib/tesla/mock.ex @@ -226,7 +226,16 @@ defmodule Tesla.Mock do end defp pdict_set(fun), do: Process.put(__MODULE__, fun) - defp pdict_get, do: Process.get(__MODULE__) + + # Gets the mock fun for the current process or its ancestors + defp pdict_get do + pid_holder = + Enum.find(Process.get(:"$ancestors", []), self(), fn ancestor -> + !is_nil(Process.get(ancestor, __MODULE__)) + end) + + pid_holder |> Process.info() |> Keyword.get(:dictionary) |> Keyword.get(__MODULE__) + end defp agent_set(fun) do case Process.whereis(__MODULE__) do diff --git a/test/tesla/mock_test.exs b/test/tesla/mock_test.exs index b1b5ced3..22244e7d 100644 --- a/test/tesla/mock_test.exs +++ b/test/tesla/mock_test.exs @@ -84,6 +84,17 @@ defmodule Tesla.MockTest do assert env.status == 201 assert env.body == %{"id" => 42} end + + test "mock a request inside a spawned process" do + task = + Task.async(fn -> + assert {:ok, %Tesla.Env{} = env} = Client.get("/json") + assert env.status == 200 + assert env.body == %{"json" => 123} + end) + + Task.await(task) + end end describe "without mock" do