Method: PageObject::Accessors#element

Defined in:
lib/page-object/accessors.rb

#element(name, tag = :element, identifier = { :index => 0 }, &block) ⇒ Object

adds three methods - one to retrieve the text of an element, another to retrieve an element, and another to check the element’s existence.

Examples:

element(:title, :header, :id => 'title')
# will generate 'title', 'title_element', and 'title?' methods

Parameters:

  • the (Symbol)

    name used for the generated methods

  • the (Symbol)

    name of the tag for the element

  • identifier (Hash) (defaults to: { :index => 0 })

    how we find an element.

  • optional

    block to be invoked when element method is called



996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/page-object/accessors.rb', line 996

def element(name, tag=:element, identifier={ :index => 0 }, &block)
  #
  # sets tag as element if not defined
  #
  if tag.is_a?(Hash)
    identifier = tag
    tag        = :element
  end

  standard_methods(name, identifier, 'element_for', &block)

  define_method("#{name}") do
    element = self.send("#{name}_element")

    %w(Button TextField Radio Hidden CheckBox FileField).each do |klass|
      next unless element.element.class.to_s  == "Watir::#{klass}"
      self.class.send(klass.gsub(/(.)([A-Z])/,'\1_\2').downcase, name, identifier, &block)
      return self.send name
    end
    element.text
  end
  define_method("#{name}_element") do
    return call_block(&block) if block_given?
    platform.element_for(tag, identifier.clone)
  end
  define_method("#{name}?") do
    self.send("#{name}_element").exists?
  end
  define_method("#{name}=") do |value|
    element = self.send("#{name}_element")

    klass = case element.element
            when Watir::TextField
              'text_field'
            when Watir::TextArea
              'text_area'
            when Watir::Select
              'select_list'
            when Watir::FileField
              'file_field'
            else
              raise "Can not set a #{element.element} element with #="
            end
    self.class.send(klass, name, identifier, &block)
    self.send("#{name}=", value)
  end
end