Skip to content
Scott Clark edited this page May 5, 2016 · 11 revisions

When a class is extended with this module a method named def_elements is provided, which can be used to define instance methods on a class for getting elements. It accepts the name (not an actual reference, e.g. :@my_var not @my_var) of the instance variable containing a "root element" instance (e.g. a browser instance) and a hash of key-value pairs used to define methods for accessing certain elements where the key is the name of the method to be defined and the value is an array whose first element is the name of the method to be called on the root element and whose subsequent elements are the arguments to be used when calling that method. For example, the following:

def_elements(:@browser, {
  :username_field => [:text_field, :id => 'username'],
  :password_field => [:text_field, :id => 'password'],
  :log_in_button => [:button, :value => 'Log In']
})

is equivalent to the following:

def username_field(selectors = {})
  @browser.text_field({:id => 'username'}.merge(selectors))
end

def password_field(selectors = {})
  @browser.text_field({:id => 'password'}.merge(selectors))
end

def log_in_button(selectors = {})
  @browser.button({:value => 'Log In'}.merge(selectors))
end

Note that the defined methods accept additional selectors as an optional parameter. This is useful for situations where you may have a collection of similar elements for which you wish to access individual elements using one-off selection criteria, such as the text it contains. For example:

# In your page object
def_elements(:@browser, {
  :user_table_row => [:div, :class => 'table-row']
})

# Later on in your code
page.user_table_row(:text => /John Smith/)
Clone this wiki locally