Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test in Capybara that a page has *not* reloaded (JavaScript onClick intercept has worked)?

I am using Capybara, Cucumber and Poltergeist. I am testing a JavaScript function that is attached to a form submit button, which is intended to catch the submit event and prevent it (doing an AJAX request in the background). With and without AJAX, the page will end up looking the same, but the AJAX approach is much faster and does not interrupt the browsing experience etc.

What can I do to test that the form was indeed not submitted, and that the changes are the result of a dynamic AJAX call rather than a reload?

like image 695
Matt Gibson Avatar asked Nov 27 '13 13:11

Matt Gibson


1 Answers

Modified version of @jules' answer:

describe "My page", :js do
  it "reloads when it should" do
    visit "/"

    expect_page_to_reload do
      click_link "Reload me"
    end
  end

  def expect_page_to_reload
    page.evaluate_script "$(document.body).addClass('not-reloaded')"
    yield
    expect(page).not_to have_selector("body.not-reloaded")
  end
end

EDIT 2017-01-19:

I found this old answer of mine which strangely did not seem to answer the actual question, but instead the opposite (check that the page has reloaded). This is what we do currently in our app to check that a page does not reload:

def expect_page_not_to_reload
  page.evaluate_script %{$(document.body).addClass("not-reloaded")}
  expect(page).to have_selector("body.not-reloaded")
  yield
  sleep 0.5  # Give it a chance to reload before we check.
  expect(page).to have_selector("body.not-reloaded")
end

Both answers rely on jQuery for adding the class.

like image 167
Henrik N Avatar answered Nov 14 '22 22:11

Henrik N