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.
Last Post!
peerreynders
it will ignore it, correct?
If I understand the source correctly it won’t even compile.
Could someone give me an example?
i.e. it doesn’t look like it is any different from using on_exit/1 inside a regular setup block. on_exit registers a function to perform the teardown (and if the function is created inside the block is has access to anything inside of the block).
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









