Testing environment variables in an Elixir/Phoenix application
Use the Application.put_env method to override environment variables for your unit and integration tests.
Assuming you go with a similar approach to set environment variables using my previous post on this subject, you can test the different values using an approach like the following example, which asserts that if the stealth_mode
configuration value is set to "1"
that it should redirect to a beta waitlist route, and if set to "0"
it should render the home page route.
defmodule MyAppWeb.HomeLiveTest do
use MyAppWeb.ConnCase
import Phoenix.LiveViewTest
test "/ path redirects to waitlist when stealth_mode is true", %{conn: conn} do
Application.put_env(:my_app, MyAppWeb.StaticConfiguration, stealth_mode: "1")
{:error, redirect} = live(conn, ~p"/")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/waitlists/beta"
assert Map.equal?(%{}, flash)
end
test "/ path renders home page when stealth_mode is false", %{conn: conn} do
Application.put_env(:my_app, MyAppWeb.StaticConfiguration, stealth_mode: "0")
{:ok, _view, _html} = live(conn, ~p"/")
end
end
As you can see the important part of this is setting the environment variables as needed for your tests using this method call: Application.put_env(:my_app, MyAppWeb.StaticConfiguration, some_value: "SOME_VALUE_FOR_MY_TEST")
One tiny gotcha is that this method will set all configuration values for the module that you've created, so make sure to pass in all of the environment variables that you need for your test to pass.
Happy coding! SL