简体   繁体   中英

Phoenix: How to get conn %Plug.Conn{} in the console

After

iex -S mix phx.server

I want to do some quick tests in the iex terminal, but some functions require the struct %Plug.Conn{} as an argument, for example I wanted to get the result of expression:

MyAppWeb.Router.Helpers.confirmation_url(%Plug.Conn{}, :edit, "12345")

But I've got error:

Phoenix endpoint not found in %{}

Is there a simple way of getting conn struct in the console?

Router helper functions accept either a conn or an endpoint module as the first argument. You can pass the endpoint module of your app when you want to generate a URL without a conn:

MyAppWeb.Router.Helpers.confirmation_url(MyAppWeb.Endpoint, :edit, "12345")

Edit: If you want to create a dummy conn that works with Router helpers, it seems like it's enough to put a %{phoenix_endpoint: MyAppWeb.Endpoint} value in conn.private as of Phoenix 1.3:

conn = %Plug.Conn{private: %{phoenix_endpoint: MyAppWeb.Endpoint}}
MyAppWeb.Router.Helpers.confirmation_url(conn, :edit, "12345")

The ConnCase test helpers use Phoenix.ConnTest.build_conn() to bootstrap a connection struct for the controller tests.

You can find the function here and either use it directly or follow its implementation and tweak it as you like.

Why spending time with testing on the console. Just write a test and use the 'ConnCase' which gives you the conn struct in your tests for free. During development you can also use the "test watch" package which will rerun your tests on every file change.

As soon as you switch to tdd as more time you will save with problems like this

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