Search code examples
elixirplug

How do I call the route defined by the Plug.Router macro at runtime?


Can I manually build a conn and then call them like a function? If you don't understand what "them" means, look at the code below.

For example, define a route /ping

get "/ping" do
  send_resp(conn, 200, "pong")
end

I know that it can be done with the conn function in use Plug.Test, but it is based on the HTTP Client, not a runtime function call, which is too inefficient.


Solution

  • The standard way is as you said, to use Plug.Test.conn/3 to build a %Plug.Conn{} struct that will cause that route to be called.

    All plugs have a call/2 function, which is what's available at runtime.

    Example:

    conn = Plug.Test.conn(:get, "/ping", "")
    conn = YourModule.Router.call(conn, [])
    

    The get macro is compiled at compile-time into a private match/3 function, which itself is called by the call/2 function and also requires the conn struct. So you have to use the call/2 callback for runtime testing, unless you call match/3 from inside your router module. Plug.Test.conn/3 does not use an HTTP Client - it's just produces a struct. I think your concerns about inefficiency are unfounded.