Ajax Calls

Justin Ko edited this page Feb 18, 2016 · 12 revisions

The secret to working with Ajax is having the ability to wait until different page events occur. The page-object gem supports waiting at two different levels - the page level and element level. Let's look at both.

Page level waiting

On the PageObject module (and therefore on your page objects) there is a method that assists with waiting.

  def wait_until(timeout = 30, message = nil, &block)

This method will wait until the passed in block returns true. If the block does not return true within the specified timeout seconds then an error is thrown with a default message or the provided message. Let's take a look at how we might use this.

  @page.wait_until do
    @page.text.include? "Success"

In the example above we are using the default timeout and message. This code will wait until the page includes the text "Success". Let's look at another example.

  @page.wait_until(5, "Call not returned within 5 seconds") do
    @page.text.include? "Value returned from Ajax call"

In this example we are setting the timeout to 5 seconds and providing a custom message.

Element level waiting

On the Element class we have several methods to assist with waiting.

  def when_present(timeout = 5)
  def when_not_present(timeout = 5)
  def when_visible(timeout = 5)
  def when_not_visible(timeout = 5)
  def wait_until(timeout = 5, message = nil, &block)

The usage of the first three methods are fairly self explanatory. They will simply wait until the element is present, visible, or not visible and then return the element. If the wait exceeds the timeout value then an error occurs. Let's look at a simple example


In this code we are waiting until a link defined by a call to link(:foo, :id => 'cont') is visible and then we are clicking it.

There are times when you want to wait for something other than the element being present or visible. The last wait call wait_until is for you. It will wait until the block returns true.