Search code examples
terminalelixirphoenix-frameworkplug

Phoenix: How to test controller actions from the console?


I have created a new controller action and I would like to test it from the console to make sure it works.

How can I execute the action after running iex -S mix phx.server in the terminal? It seems to me that in order to do this, I need to create a conn struct as well as a user struct (since I am using Guardian).

My controller code looks like this:

defmodule HelloWeb.AssetController do
  use HelloWeb, :controller
  use Guardian.Phoenix.Controller

  action_fallback HelloWeb.FallbackController

  def new_action(conn, %{"id" => id}, user, _claims) do
    # Stuff I want to test
  end

  # Other actions omitted

end

How can I test new_action from IEx?


Solution

  • You can use phoenix test helpers to achieve something like what's done in the ExUnit tests in iex:

    iex(22)> conn = Phoenix.ConnTest.build_conn() |>
    ...(22)> Phoenix.Controller.put_view(HelloWeb.AssetView)
    %Plug.Conn{...}
    
    # This assumes you have at least one user created in the dev database
    iex(23)> [user | _] = HelloWeb.Schemas.User |> HelloWeb.Repo.all
    
    iex(23)> HelloWeb.AssetController.new_action(conn, %{"id" => some_id}, user, [])
    # You can inspect this conn to see if what's rendered is OK
    %Plug.Conn{...}