Change config compile env variables during ExUnit test

Hi,

I have some compile env and I want to change their values in some specific test cases and then change them back.
Is there any way of doing that? recompile/1 is not working as this function simply recompiles Elixir modules, without reloading configuration, recompiling dependencies, or restarting applications.
I think that I need to reload the configuration too.

Best regards.

How are you accessing their values?

You can use Application.put_env/3, however you need to be careful with asynchronous tests as application environment is global.

In config.exs config :app, :retry

I access them by using Application.compile_env/3

I assume as module variables @… then I think the only way to do it is to change them in test.exs.
As far as I know these are replaced during compilation by their respective values, so changing the config in a test will yield nothing. Though I must say I do not see a how a compile time variable could need to be changed in a test. If this is a variable that can change it should not be compile time.

There is no way to recompile the app during tests?

Application.put_env/3 does not change compile time variable

recompiling during tests doesn’t make sense. it’s the same as recompiling while a server is running.

feels like a XY problem. what are you actually trying to accomplish?

To test the usage of compile env variables. I have default values in case comp_env are not provided. I need to make a test case when I change their value

one option is to have separate config files, but then you would have to run with MIX_ENV=test_this mix test. does this solve it?

but what are you testing exactly? why are compile time variables changing?

i’m pretty sure you don’t need to test if compile time variables work, that’s elixir. you can trust elixir. you probably want to test what happens in your code with different values for that variable. in that case just hardcode the variable into the test. meaning ignore the env var and create a new one, then pass it into the function/process you’re testing.

if it turns out that your code uses the env var in the function you’re testing, well then make the value an argument in the function so the test can pass it in (which is usually a good idea in terms of good code anyway).

1 Like

It is a library with ability to change the default options(which are compile time env) on Application level in projects which are using it by setting them up in config.exs `config :app, :retry, new_default’

For libraries you should avoid compile time config and even using the app env:
https://hexdocs.pm/elixir/library-guidelines.html#avoid-application-configuration

2 Likes

I get that, but that is my task so I was wondering if I could test it or not. Seems that I can not do that.

Why not create a validation function for the config, and test that?
Then maybe compilation could fail when something invalid is given.

1 Like