polypush135
Following redirection in ControllerTests
Say I have a controller like so.
def create_pass_reset(conn, %{"user" => %{"email" => email}}) do
case Accounts.reset_pass(email) do
{:ok, user} ->
conn
|> put_flash(:info, "Password Reset Sent to #{user.email}")
|> redirect(to: session_path(conn, :new))
...
end
end
Note that I am setting a flash on a conn that is due to be redirected.
And say I have a test like so.
test "POST /password-reset", %{conn: conn, user: user} do
conn = post conn, user_path(conn, :create_pass_reset, %{"user" => %{"email" => user.email}})
assert redirected_to(conn, 302) =~ "/login"
assert html_response(conn, 302) == "Password Reset Sent to #{user.email}"
end
Well clearly the issue with this test is that the conn does not contain the state after the redirection occurred and thus does not have the content we are looking for
IE:
Assertion with == failed
code: assert html_response(conn, 302) == "Password Reset Sent to #{user.email()}"
left: "<html><body>You are being <a href=\"/login\">redirected</a>.</body></html>"
right: "Password Reset Sent to email-11@example.com"
So my question is, how do I perform the redirect so that I can see the state after the redirection has occurred?
Marked As Solved
chrismccord
Something like this should work:
conn = post conn, user_path(conn, :create_pass_reset, %{"user" => %{"email" => user.email}})
assert "/login" = redir_path = redirected_to(conn, 302)
conn = get(recycle(conn), redir_path)
assert html_response(conn, 302) == "Password Reset Sent to #{user.email}"
Also Liked
kplattret
Yes indeed, recycle/2 gives you a fresh connection with no assigns, so you need to save them prior to calling it and make sure you put them again. I encountered the same scenario and found a solution here: Why Phoenix Recycling?
chrismccord
It’s just fine pattern wise. It’s not exactly the same, but our context generators make use of redirected_params to construct a path and then get the show page of a created resource:
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








