Testing mounts with `get_connect_info/2`

I’m working in Phoenix 1.7.0-rc.2 and have updated LiveView to 0.18.9.

I added some on_mount/4 hooks and, specifically, added functionality to on_mount(:mount_current_user, ...) to grab info like the user agent and IP address which uses get_connect_info/2. In dev this works as expected.

Since I am testing the mounting functions in isolation without going through the routes, the connect info isn’t getting set in private.

Is there a good way to load in connect info for the purposes of testing in isolation like this? The sample tests just drop in a new LiveView.Socket. Obviously I can just populate private with some connect info but that’s not ideal. (It is what I am going to do in the meantime, lol.)

While I would typically test LiveView stuff on the views themselves, the mounts should be tested in isolation and the examples in mix phx.gen.auth do exactly that.

There used to be a test helper put_connect_info/2 that would set private field for us. Now

This function is deprecated. set the relevant connect_info fields in the connection instead.

Though, I’d like to point that there is Plug.Test.put_peer_data/2

So I think it’s totally fine to have something like:

conn = put_peer_data(conn, %{address: {0, 0, 0, 0}, port: 80})
socket = %LiveView.Socket{private: %{connect_info: conn}}

and pass it to on_mount/3

I know, using :private seems like leaking implementation details to the test as that field is “reserved for the library/framework usage”[0] but at this point we are testing on_mount/3 callback which is also in some sense leaks the details of the framework (the lifecycle).

While I would typically test LiveView stuff on the views themselves, the mounts should be tested in isolation and the examples in mix phx.gen.auth do exactly that.

Agree, on_mount/3 is meant to be reusable. Hence, it makes sense to test it separately. However, I would still add some other integration tests for “LiveView stuff on the views themselves” to make sure that the behaviour, implied by on_mount/3, is preserved :slightly_smiling_face:


[0] - Plug.Conn # Private fields

I’ve done a thing before where I make a macro that can be injected into into any test files for live views that I want to ensure have the included mounting behaviour. I think it’s fine to test the mounts in isolation if that is what you prefer, but for me it just adds test noise that isn’t very helpful beyond TDD design feedback (at which I point I would just delete the test when I was done). YMMV, of course. Just my two cents!

EDIT: clarify language around scope of macro… it doesn’t magically inject into the tests it needs to be in… you manually call it in the tests you need it in.

1 Like