# Keeping self() straight in on_exit callbacks

An `on_exit` callback looks like it belongs to the test that registered it, but `self()` inside the callback is not the test PID:

```elixir
test_pid = self()

on_exit(fn ->
  IO.inspect(self() == test_pid)
end)

#=> false
```

ExUnit runs exit callbacks in a separate process after the test process exits. It reminds me of debugging JavaScript's `this`: the name is familiar, but you still need to check which execution context you're actually in.

Capture the test PID before registering identity-sensitive cleanup:

```elixir
test_pid = self()

on_exit(fn ->
  MyRegistry.release(test_pid)
end)
```

Capturing the PID does not keep the test process alive. Use it only when the cleanup API needs the original PID as an ownership key; you cannot send work back to the finished test. ExUnit also stops processes started with `start_supervised/2` before it runs `on_exit` callbacks.

https://hexdocs.pm/ex_unit/ExUnit.Callbacks.html#on_exit/2


---

Created by: almirsarajcic
Date: September 18, 2026
URL: https://elixirdrops.net/d/i4LKDQFf
