Selenium Tutorial: Pageobject

10. PageObject

  • PageObjects is a design pattern where objects representing your pages are exposed to the test logic as services providing access to the elements and logic of your page
  • The pattern is defined along the following:

    • The public methods exposes the services the page offers
    • The internals of the page should not be exposed
    • Don’t make assertions in the PageObject class, it is the test logic’s work
    • Methods return other PageObjects
    • You don’t need to represent an entire page, just the services you need to test
    • One action can have several methods depending on the result of these actions
  • PageObjects' methods exposes actions on the page (a login action for instance) and must return another PageObject:

    class LoginPage
    
        @error_message
    
        def loginAs(username, password) 1
            # ...
            HomePage.new
        end
    
        def loginAsExpectingError(username, password) 2
            # ...
            # error_message = something
            self
        end
    
        def error_message
            @error_message 3
        end
    public class LoginPage {
    
        private String errorMessage;
    
        public HomePage loginAs(username, password) { 1
            ...
            return new HomePage();
        }
    
        public LoginPage loginAsExpectingError(username, password) { 2
            ...
            errorMessage = something;
            return self;
        }
    
        public void getErrorMessage() {
            return errorMessage; 3
        }
    }

    1 1

    Once logged-in, the server redirects to the home page so the login methods should return a PageObject representing the homepage

    2 2

    We test a failed login gives the correct message. Since it is a failed login, we stay on the login page so we return the same object

    3 3

    We can return here the error message displayed on the page in case of failed login
  • The PageObject pattern is a good practice because:

    • It facilitates code reuse: think about inheritance and abstract classes
    • It facilitates maintenance: code logic and page are separated

10.1. Lab 6: PageObject Pattern

  • We’re going to transform our tests to follow the PageObject pattern

10.1.1. Java

  • You will find in the project in the labs/lab6/java folder a Page class as well as a Lab6 containing the test to run
  • The Page class is the class from which all your projects will inherit from
  • The Lab6 class contains the test and therefore, the methods to implement in your page objects

10.1.2. Ruby

  • At first you’ll have the lab6.rb file which is the test spec, as well as a page.rb file containing a Page class from which all your PageObject are going to inherit from
  • Use the spec to find which methods to implement
  • Reuse your previous work to build upon