While developing tests in Ruby, we can use the page-object gem to implement the Page Object model within the tests. The page-object gem provides simple features with which to build the objects of a Page Object, along with Watir WebDriver.
In this recipe, we will see how to use the page-object gem to implement the Page Object model for the BMI Calculator's main page.
You need to download and install the page-object gem with the help of the following command:
gem install page-object
To implement the Page Object model in Ruby using the page-object gem, perform the following steps:
require 'page-object' class BmiCalcPage include PageObject text_field(:height, :id => 'heightCMS') text_field(:weight, :id => 'weightKg') button(:calculate, :value => 'Calculate') text_field(:bmi, :id => 'bmi') text_field(:bmi_category, :id => 'bmi_category') def calculate_bmi(height, weight) self.height = height self.weight = weight calculate end def open() @browser.get ' http://cookbook.seleniumacademy.com/bmicalculator.html' end end
BmiCalcPage
class, create a test for the calculation feature, as follows:require 'rubygems' require 'watir-webdriver' require 'test/unit' require_relative 'bmicalcpage.rb' class BmiCalcTest < Test::Unit::TestCase def test_bmi_calculation @driver = Selenium::WebDriver.for :chrome bmi_calc = BmiCalcPage.new(@driver) bmi_calc.open() bmi_calc.calculate_bmi('181','80') assert_equal '24.4', bmi_calc.bmi assert_equal 'Normal', bmi_calc.bmi_category @driver.close() end end
We can use the Page Object model implemented with the page-object gem by creating an instance of the BmiCalcPage
class and passing the browser as an argument to the constructor. The rest of the magic is performed by the page-object gem.
While defining the elements, we need to specify the type of element and the locator, as follows:
text_field(:Height, :id => 'heightCMS')
The page-object gem adds a few more methods automatically to these objects at runtime. For example, we created an element for the Calculate
button in the Page Object model, as follows:
button(:Calculate, :value => 'Calculate')
The page-object gem creates a method called calculate
, which will click the Calculate
button when called from the calculate_bmi()
method, as follows:
def calculate_bmi(height, weight) self.height = height self.weight = weight calculate end
You can find more information about the page-object gem API at http://rubydoc.info/github/cheezy/page-object/master/PageObject/Accessors.
3.145.81.98