Tracing and asserting function calls

Expanded my code now like this:

def setup_trace(%{trace: mfas}) when is_list(mfas) do
  {:ok, pid} = Agent.start_link(fn -> %{} end)

  :dbg.start()

  :dbg.tracer(
    :process,
    {fn {:trace, _pid, :call, {mod, fun, args}}, _state ->
      Agent.update(pid, fn calls ->
        Map.update(calls, {mod, fun, length(args)}, 1, &(&1 + 1))
      end)
    end, nil}
  )

  :dbg.p(:all, :c)

  Enum.each(mfas, fn {mod, fun, arity} -> :dbg.tp(mod, fun, arity, []) end)

  {:ok, pid: pid}
end

def setup_trace(%{trace: mfa}), do: setup_trace(%{trace: [mfa]})

def setup_trace(_tags), do: :ok

This allows me to assert on the calls like this:

@tag trace: {MyApp.Posts, :get_posts, 1}
test "renders list of posts", %{user: user, conn: conn, pid: pid} do
  # ...
  assert Agent.get(pid, & &1) == %{{MyApp.Posts, :get_posts, 1} => 1}
end

Will now try to wrap this in a custom macro, so it’s less boiler plate.