Fl4m3Ph03n1x
How to clean up after each test inside describe?
Background
I have a test file with several describe blocks, each one with a custom setup block, like the following:
defmodule MyAppTest do
use ExUnit.Case
describe "group 1" do
setup do
:persistent_term.put("hello", :world)
:ok
end
test "test 1" do
assert true
end
test "test 2" do
assert true
end
end
# describe group2 ....
end
Here I am setting up a persistent term that I will use along the app. Now, once I reach the end of all tests in the describe block, I want to clean up, meaning I want to delete the "hello" entry from :persistent_term.
To achieve this I am aware of on_exit, but according to my understanding, this callback is only executed once at the end of all tests from all describe blocks.
Questions
- Is my understanding of
on_exitcorrect? - How can I run a clean up function after the tests of each
describeblock?
Most Liked
josevalim
setup is always executed per test and on_exit will always respect the context it is called in. On exit in setup runs after the test. On setup all, after all tests, etc.
idi527

on_exit in a setup block is executed after each test, in my experience. I’ve never tried using on_exit in setup_all though.
josevalim
It will run once for each test in the describe block. But since it is a side-effect, it will be leaked to other tests.








