0
votes

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
1
Can you clarify what you mean by an action?Gazler
Do you mean this conn = put_private(conn, :phoenix_action, :action_name) (replace :action_name with the action's name)?Dogbert
If not, could you post the source of the Plug? I'm not sure I understand the question.Dogbert
@Gazler I mean a controller action (new, create, index, etc). When I pass the option except: [:create, :new] into the plug, it shouldn't do some checks when the action is either :create or :new. So for testing this I need to be able to call a specific action in my tests.Ole Spaarmann
@Dogbert Thank you, that did the trick!Ole Spaarmann

1 Answers

1
votes

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])