How can I force a clear "stack" in cargo test

I'm currently writing some tests for a library using dotenv.
I want to test the behavior of the library when certain configurations in the .env file change.
Thus I have written several tests that all in the beginning initialize the dotenv using dotenv::from_filename.

I'm passing different .env files depending on the configuration I want to test.
The problem is that the way dotenv is written seems like it just keeps it's configuration once it was successfully initialized.

This means that if I first test a "good" configuration including valid properties, and afterwards test one that uses invalid ones, expecting missing properties, the second test will fail because the properties are actually present.
This is especially a problem when running tests in parallel.
So what I need would be a clear application "stack" separated for each test so that dotenv can initialize multiple times.
Is there any way to tell rust that it needs to clear the memory for each test of a specific list of tests?
Some sort of macro maybe.

You will have to turn off parallel tests. If you do that, you can use remove_var at the start of each test.

1 Like

If I could, I would give you multiple hearts.
Helpful and super fast as always.

You probably shouldn't be using dotenv as part of your tests. Instead I'd pull the state you need out into its own struct that is created for each test (you may want to pull that bit out into a helper function).

Avoiding this sort of global state tends to make your tests more reliable and you don't run the risk of forgetting to call remove_var() at the start of every test.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.