Testing a LiveView form with csrf token

I’ve found a bunch of info on what I’m about to ask here but all a little vague. Or at least, the answers are direct but lack the context I’m looking for.

In a nutshell, is it necessary to manually render the csrf_token in a LiveView form, or does LiveView already handle csrf verification?

If the answer is “yes”, are there testing facilities for this? Using the standard ConnCase along with importing LiveViewTest doesn’t send the token through the setup context.

Thanks!


example:

defmodule MyApp.PageLive do
  use MyApp, :live_view

  def mount(_, %{"_csrf_token" => csrf_token}, socket) do
    changeset = MyApp.Context.changeset_something()

    {:ok,
      socket
      |> assign(:csrf_token, csrf_token)
      |> assign(:changeset, changeset)}
  end

  def render(assigns) do
    ~L"""
    <%= f = form_for @changeset, "#", phx_submit: "something-changed", csrf_token: @csrf_token %>
      <%= submit f, "Submit" %>
    </form>
    """
  end

  def handle_event("something-changed", socket) do
    # ...
    {:noreply, socket}
  end
end

Ehn, I realized what I did. I had submit "Change email instead of submit f, "Change email. D’oh.

1 Like