简体   繁体   English

Phoenix / Elixir:如何使用Plug.Test.conn()在测试连接中设置操作?

[英]Phoenix/Elixir: How to set the action in a test connection with Plug.Test.conn()?

I wrote a little plug that accepts a list of actions as options. 我写了一个小插件,它接受一系列动作作为选项。 When the action that is currently called is in this list, the plug will behave differently. 当当前调用的动作在此列表中时,插头的行为将有所不同。

For testing this I need to set the action in my unit tests. 为了进行测试,我需要在单元测试中设置操作。 Is this possible? 这可能吗? I didn't find anything in the docs. 我没有在文档中找到任何东西。

This is the short example given in the Docs of Plug. 这是插件文档中给出的简短示例。

defmodule MyPlugTest do
  use ExUnit.Case, async: true
  use Plug.Test

  @opts AppRouter.init([])

  test "returns hello world" do
    # Create a test connection
    conn = conn(:get, "/hello")

    # Invoke the plug
    conn = AppRouter.call(conn, @opts)

    # Assert the response and status
    assert conn.state == :sent
    assert conn.status == 200
    assert conn.resp_body == "world"
  end
end

I would consider integration testing these in your controller tests. 我会考虑在您的控制器测试中进行集成测试。 Since the conn.private storage is designed for libraries, it is liable to change at any time. 由于conn.private存储是为库设计的,因此随时可以更改。

If you are not concerned about it changing in Phoenix, then you can do something like: 如果您不关心Phoenix中的更改,则可以执行以下操作:

conn =
   conn(:get, "/hello")
   |> put_private(conn, :phoenix_action, :index)
   |> AppRouter.call(conn, [:index])

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

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