Testing a full redirect to a subdomain between LiveViews

I have a LiveView with a form for creating a subdomain. Once the form is submitted, I want to redirect the user to the new subdomain.

My first question is, I am right that :external should be used in the redirect?

  {:noreply, redirect(socket, external: make_path(subdomain_slug)}

If so, is it possible to test this with LiveViewTest?

I’m trying:

  lv
  |> form("#form", %{...})
  |> render_submit()
  |> follow_redirect(conn, "http://expected.sub.domain")

And I end up with:

:erlang.iolist_to_binary(["http", "://", "expected.sub.domain", "", nil, ""])

I get this whether or not I use follow_redirect/3 or follow_redirect/2 (ie, I don’t pass the expectation as the third parameter).

Any help would be appreciated, though I’m largely hoping that because I finally asked that I’ll figure it out in the next two mins, lol.

Thanks!

EDITED to clarify: I have subdomains working locally—expected.sub.domain is set up in my /etc/hosts (it’s not actually called that, of course). I am thinking I’m taking the wrong route here as this would probably problematic running tests in CI.

I would agree. follow_redirect actually visits the url you redirect to - that’s fine if it’s a local url served by your application, otherwise your test is gonna visit an external url (you probably don’t want that) or you’ll have to make sure the url resolves to some location under your control.

I suspect you figured this out already, but how about using assert_redirect/3 & friends? That doesn’t follow the url you redirect to.

EDIT: follow_redirect and friends don’t even work with non-local urls.

1 Like

I had not figure this out yet because I got distracted by this forum then pivoted. Thank you so much!

I’m at the point where I’ve written a lot LiveView tests but I continually get tripped up that I’m testing a GenServer and there’s (functional) mutation happening. Despite how the docs outline the assert_redirect functions, my initial intuition was to pipe render_submit into assert_redirect which of course didn’t work. I got there, though!

test "user can create a whosiwhatsit with a subdomain", %{conn: conn} do
  {:ok, lv, _html} = live(conn, ~p"/")

  lv
  |> form("#create-whosiwhatsit-form", %{
    whosiwhatsit: %{
      slug: "some-slug"
    }
  })
  |> render_submit()

  assert_redirect(lv, "http://some-slug.localhost:4002")
end

Thanks again, and thanks for LiveSelect! I haven’t used it yet but intend to on this project I’m working on.

1 Like

Oh nice! If you do, I’d love to hear your feedback.