1

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?

Erik Eng
  • 121
  • 7
  • What’s wrong with testing it with `ExUnit`? Also, if you want it to be interactive, just `curl` the endpoind. – Aleksei Matiushkin Oct 21 '18 at 17:46
  • @AlekseiMatiushkin I want an interactive way to do it which rules out `ExUnit`. I agree I could also use `curl` but then I would have to authenticate first and pass the token, which to me seems like more work than just grabbing a user from the repo as in the accepted solution. – Erik Eng Oct 22 '18 at 15:41

1 Answers1

2

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{...}
Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70