Capybara triggering `onload` event when using the back button

Skip to first unread message

Shawn Isenhart

Jan 18, 2022, 6:10:48 PMJan 18
to Capybara

I noticed an odd behavior in my tests today, and I was curious if this is expected behavior.  I'm testing a story where the user uses the back button.  The behavior in my browser and the behavior in the test did not match.  A snippet from the test:

    visit root_path

    expect(page).to have_selector("#room-list", visible: true)

    within("#room-list") do
      click_on sample_room

    expect(current_path).to eq(sample_room_path)


    expect(location_any_checkbox.checked?).to eq(false)
    expect(room_type_any_checkbox.checked?).to eq(false)

What is interesting is that this page has some "onload" javascript that sets up the checkboxes we are expecting.  When we do this test in the browser, it fails.  When we do it in capybara, it succeeds.

After poking around, I confirmed that in modern browsers, when you hit the back button you load the cached version of the page which explicitly does _not_ send the `load` event.  But it looks like capybara is sending the load event - as if `page.go_back` is actually re-visiting the page in history, not loading the cached page.  I put an alert on a page that would trigger on load, and capybara encountered it both when visiting the page for the first time and when going back to it via `page.go_back`, but when using chrome I only encountered it when first visiting the page, not when I came back to the page via the back button.

Is this expected behavior?  If so, is there a way to test the behavior of the back button in capybara?



Thomas Walpole

Jan 24, 2022, 4:39:27 PMJan 24
to Capybara
Sorry for the delay in an answer.  Assuming you're using Chrome via selenium, Capybara is just calling the `back` method in selenium which ends up calling the w3c defined - - back method in crhomedriver which SHOULD be identical to the user pressing the browsers back button.  If it's not then that would be a bug in chromedriver.  Capybara doesn't send any events directly to the browser during this process.
I will say that depending on onload to be run is bad practice because modern browsers, depending on how much cache they have available, may cache the page in memory and just redisplay from there at their own discretion (ie it's not guaranteed it will always redisplay from an in-memory cache).  You may want to investigate the `pageshow` event instead -

Shawn Isenhart

Jan 25, 2022, 2:38:23 PMJan 25
to Capybara
Thanks for the reply!  We're looking at rebuilding that code so we don't rely on the onload event, but the tricky part was that we didn't realize that we needed to look at this change since the Capybara tests were passing just fine.  Very surprising!  I'll look into reporting this as a bug in chromedriver, and see where that goes.
Reply all
Reply to author
0 new messages