0

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.

Hentioe
  • 228
  • 1
  • 9

1 Answers1

1

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.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • Yes, the `conn` function only generate a struct. But is `MyModule.Router.call` based on an HTTP client? Sorry, this is just my subconscious speculation. – Hentioe Feb 19 '19 at 02:40
  • No, `call/2` is just a regular function call. That function is eventually called when your application handles an HTTP request - in that case the adapter (probably `plug_cowboy`) handles producing the `conn` for you - but there's no reason you can't also make your own `conn` using `Plug.Test.conn/3` and call `call` directly. – Adam Millerchip Feb 19 '19 at 02:55