We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Keeping self() straight in on_exit callbacks
almirsarajcic
An on_exit callback looks like it belongs to the test that registered it, but self() inside the callback is not the test PID:
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:
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.
copied to clipboard