Testing LiveView with different Locales


I am trying to test a registration form where I’d like to capture the user’s locale. I can test my code manually and this works fine, but I cannot figure out how to change the locale in a test.

      Gettext.with_locale(MyApp.Gettext, "de", fn ->
          {:ok, lv, _html} = live(conn, ~p"/register")

I also tried Gettext.put_locale(MyApp.Gettext, "de") and setting the locale on conn via conn = Plug.Conn.put_session(conn, :locale, "de").

What am I missing? Any other ways to get this done?

Background on capturing locale: I put MyApp.get_locale(PetalProWeb.Gettext) in a @locale and capture it via a hidden field in the registration form.

Thanks in advance!

The LV is a separate process. Gettext.with_locale (and basically all other ways of setting and retaining a locale) is per process. So you’re setting the locale for the test process, not the LV handling client.

You’ll need to run Gettext.put_locale within the LV process (e.g. as an on_mount callback) and at best you control that from the test the same way you pass the locale to LV in production.

1 Like

Yes. That is what I needed to do. My app already supports setting locale via URL params. Simple as live(conn, ~p"/register?locale=de")

All these much harder paths I tried! Argh!