without_page_refresh capybara helper

March 22, 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

Dmitriy Kalinin is a Software Engineer at Pivotal working on Kubernetes and Cloud Foundry projects.

Follow on Twitter 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
Why I'm not a Smartphone User (I'm an iPod user)
Why I'm not a Smartphone User (I'm an iPod user)

I have a confession. I don’t own a smartphone. I’ve been a mobile developer for 7 years having started on ...