Page Objects
The Page Object pattern is a way to represent pages and their elements in reusable classes. Page Objects eliminate duplication by building an abstraction that allows you to write browser tests for maximum maintainability and robustness.
The Page Object pattern originated in WebDriver, and a great explanation (with examples in Java) can be found here.
You create a Page object for each page of your application, which has methods that represent the services available on a given page. You should encapsulate all the implementation details of the system (i.e. HTML elements, waiting for the DOM to update etc) in these objects. Your test code (i.e. RSpec code blocks, Cucumber step definitions) should never access the underlying Browser instance or deal with HTML elements directly.
In essence, you should have the mindset that your test code should not need to change if your web app was rewritten as a desktop app - you would simply need another implementation of the page object layer. Although strictly speaking a set of pages isn’t necessarily a good way to model a desktop application, having this in mind makes it easy to decide what should go where.
The examples below assumes you are familiar with RSpec way of doing test assertions.
Consider this script:
With page objects, this could become:
An implementation of this could be:
This can then be integrated with other tools. For example, using Cucumber you could have this in env.rb:
And this step definition:
Assertions/expectations should be kept in your test code. Don’t use assertions in your page objects; instead ask them about their state, and assert on the result. E.g.:
See also:
Page Object gems that work with Watir-webdriver
- Cheezy’s Page Object gem for Watir-webdriver and Selenium
- The rSmart Test-Factory gem for Page & Data objects using Watir-webdriver
- WatirPump: Page Object gem - a fresh approach from 2018
Blog postings related to Page Objects and Watir-webdriver
- cheezyworld’s series on UI testing part 1, part 2, part 3, part 4, part 5
- Watermelon blog article on ‘roll your own’ page objects
- WatirPump: Page Object library for Ruby and Watir
Blog postings related to Page Objects and webdriver/Selenium