Skip to content

Creating and using page objects

osugregor edited this page Jul 2, 2012 · 10 revisions

Alister Scott blogged about an idea for creating a factory to create instances of page objects. In the past I have blogged about page objects returning page objects. After a lot of contemplation, I am completely in the Alister camp. page-object now supports this approach as well.

PageFactory

A module named PageFactory provides this ability. This module has two methods.

def visit_page(page_class, &block)
def on_page(page_class, visit=false, &block)

Let's take a look at how you would use these method in your cucumber scripts.

Given /^I am on the registration page$/ do
  visit_page RegistrationPage
end

This call will cause the browser to open the page specified by the call to page_url in the class.

class RegistrationPage
  include PageObject

  page_url "http://mysite.com/registration"
  ...
end

If you wish to perform some activity on that page when you navigate to it you can pass a block to the method.

When /^I register on the registration page$/ do
  visit_page RegistrationPage do |page|
    page.register_user
    page.do_something_else
  end
end

If you are already on a page and wish to interact with it you can use the on_page method.

Then /^I should be able to cancel my order$/ do
  on_page CheckoutPage do |page|
    page.cancel_order
    page.do_something_else
  end
end

Both methods also support a shortened version to do only one item on the page.

Then /^I should be able to cancel my order$/ do
  on_page(CheckoutPage).cancel_order
end

If you wish to interact with the current page conditionally, you can use the 'if_page' method.

Then /^I should be able to view my cart$/ do
  @current_page.check_nav_cart_exists
  if_page CheckoutPage do |page|
    #enters iff @current_page is of Page CheckoutPage
    page.check_product_list_exists
    page.do_something_else
  end
end

Note: You need some plumbing in your env.rb file under hooks to make these methods available to use

require 'page-object/page_factory'
World(PageObject::PageFactory)

You will also need to make available an '@browser' variable for the driver you wish to use.