Easiest way to render a .heex template to an HTML string?

Usually in tests of my views, I have used safe_to_string() to convert a returned :safe tuple to HTML that I can assert on. For example:

test "greets the user" do
  user = %{name: "Kurt"}
  html = MyView.render("some_template.html", user: user) |> Phoenix.HTML.safe_to_string()

  assert html =~ "Hello, Kurt"
end

However, if the template is a .heex file, this no longer works because the return struct is a %Phoenix.LiveView.Rendered{} struct, e.g.:

%Phoenix.LiveView.Rendered{
  dynamic: #Function<0.64041902/1 in PeanutButterWeb.PageView."hello.html"/1>,
  fingerprint: 29760870404026531075951007545402085092,
  root: true,
  static: ["<p>Hello, Kurt</p>"]
}

This is also true, even if I’m rendering from a plain view.

Is there a simple way to convert this struct to plain html?

Thanks :+1:

1 Like

Okay, here’s what I found after digging around for a while:

test "greets the user" do
  user = %{name: "Kurt"}
  html = MyView.render("some_template.html", user: user)
        |> Phoenix.HTML.Safe.to_iodata()
        |> IO.iodata_to_binary()

  assert html =~ "Hello, Kurt"
end

Will give the returned HTML as string, ready for assertions.

By the way, there are very good docs available about it here: Phoenix.LiveView.Engine — Phoenix LiveView v0.16.3

2 Likes