How to handle redirects in Wallaby?

546 Views Asked by At

I have a feature test written like this:

confirmation_page = visit(session, "/confirm/#{id}")
confirmation_page
    |> click(link("Decline"))
confirmation_page
    |> assert_text("You have declined.")

However the test always fails, because in controller, on click of this page, I am doing this:

 conn
    |> put_flash(:info, "You have declined.")
    |> redirect(to: Routes.group_path(conn, :show, group.slug))

So the flash is coming on the redirected page, and not the original page. How can I wait for the redirect and assert on the new page?

2

There are 2 best solutions below

1
On
  1. You can simply provide a sleep timer like :time.sleep(1000) before asserting over element.

  2. You can retry like waiting for page to be refreshed. You can use Wallaby.retry/2 to retry until window is refreshed on specific url. We can get current url of window using Wallaby.current_url/1. Code would look something like this.

1 retry = fn -> if Wallaby.current_url == "expected" do                                                                                                      
2     ┆   ┆   ┆   assert_text(confirmation_page)                                                                                                              
3     ┆   ┆   ┆ else                                                                                                                                          
4     ┆   ┆   ┆   {:error, :url_not_refreshed}                                                                                                                
5     ┆   ┆   ┆end                                                                                                                                            
6     ┆   end                                                                                                                                                 
7                                                                                                                                                             
8 assert {:ok, response} = Wallaby.retry(retry, 5000) ## default timeout option after which it 
0
On

Try to use assert_has(session, css("element ID or class", text: "You have declined."))

The assert has have build in retry so it will wait for this element to show up so I think it will solve your problem.