without_page_refresh capybara helper

March 21, 2012 Dmitriy Kalinin

I recently had to write a small capybara helper:

def without_page_refresh
  page.execute_script("window._withoutPageRefresh = 'BAM'")
  yield
  page.evaluate_script("window._withoutPageRefresh").should == "BAM", "Page was navigated away"
end

Use case:

You are building a form that gracefully degrades
when javascript is not enabled. It goes something like this:

# uses rack-test so no javascript
scenario "User can lose money in an accessible way" do
  visit "/your_account"
  page.should have_content "You have $100"
  click_button "Charge me"
  page.should have_content "You have $50"
end

Next step is to make that form do the ajax thingy.
You copy test above and switch it to use javascript driver:

# uses selenium for javascript
scenario "User can lose money with style", :js => true do
  visit "/your_account"
  page.should have_content "You have $100"
  click_button "Charge me"
  page.should have_content "You have $50"
end

Newly written test is pretty good except that it passes without
writing a single line of javascript. So here’s when that helper
comes into play. Our javascript test becomes:

# uses selenium for javascript
scenario "User can lose money with style", :js => true do
  visit "/your_account"

  without_page_refresh do
    page.should have_content "You have $100"
    click_button "Charge me"
    page.should have_content "You have $50"
  end
end

Now javascript test fails with “Page was navigated away”
since nothing is preventing that form from submiting to another page.

About the Author

Biography

More Content by Dmitriy Kalinin
Previous
How OpenCredo Launched Three New Products in Seven Months with Cloud Foundry
How OpenCredo Launched Three New Products in Seven Months with Cloud Foundry

From the beginning, Cloud Foundry has been about simplifying the development, deployment and operation of c...

Next
A Week at Xtreme Labs: An Engineer's Perspective
A Week at Xtreme Labs: An Engineer's Perspective

The intensity of downtown Toronto’s rush-hour pedestrian traffic pales in comparison to the electric work e...

Enter curious. Exit smarter.

Register Now