简体   繁体   English

Phoenix:如何从控制台测试控制器动作?

[英]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?在终端中运行iex -S mix phx.server后如何执行操作? 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).在我看来,为了做到这一点,我需要创建一个conn结构以及一个user结构(因为我使用的是 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?如何从 IEx 测试new_action

You can use phoenix test helpers to achieve something like what's done in the ExUnit tests in iex :您可以使用 phoenix 测试助手来实现类似于在iex中的 ExUnit 测试中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{...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM