简体   繁体   中英

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.

If you are not concerned about it changing in Phoenix, then you can do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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