Finding visible/hidden elements with the new :visible locator

Watir 6.0 introduces a new locator – :visible. This allows you to specify whether or not the element can be seen by the user.

Usage

Consider the following page where the first div is visible and first span element is hidden:

<html>
  <body>
    <div id="visible_div">can be seen by users</div>
    <div id="hidden_div" style="display:none;">cannot be seen by users</div>

    <span id="hidden_span" style="display:none;">cannot be seen by users</span>
    <span id="visible_span">can be seen by users</span>
  </body>
</html>

By default, Watir locates the first matching element regardless of visibility:

browser.div.id
#=> "visible_div"

browser.span.id
#=> "hidden_span"

By adding visible: true, the first matching visible element is returned:

browser.div(visible: true).id
#=> "visible_div"

browser.span(visible: true).id
#=> "visible_span"

By adding visible: false, the first matching hidden element is returned:

browser.div(visible: false).id
#=> "hidden_div"

browser.span(visible: false).id
#=> "hidden_span"

Not available for collections

In at least version 6.0.2, the :visible locator is not available for collections. Hopefully this is just an oversight and will be added in future releases – Issue 499.

browser.divs(visible: true).count
#=> C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/xpath_support.rb:5:in `escape': undefined method `include?' for true:TrueClass (NoMethodError)
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:48:in `equal_pair'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:32:in `block in attribute_expression'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:28:in `each'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:28:in `map'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:28:in `attribute_expression'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder/xpath.rb:18:in `build'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder.rb:122:in `build_xpath'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder.rb:103:in `build_wd_selector'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/selector_builder.rb:49:in `build'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/locator.rb:140:in `find_all_by_multiple'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/locators/element/locator.rb:60:in `locate_all'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/element_collection.rb:98:in `elements'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/element_collection.rb:84:in `to_a'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/element_collection.rb:28:in `each'
#=>   from watir-webdriver.rb:98:in `count'
#=>   from watir-webdriver.rb:98:in `<main>'

Performance impact

For the locator to work, Watir iterates through the elements to check their visibility. This can be seen in the Watir::Locators::Element::Locator. A wire call, el.displayed? is made for each potentially matching element:

elements = @query_scope.wd.find_elements(how, what)
elements = elements.select { |el| visible == el.displayed? } unless visible.nil?
elements[idx] unless elements.nil?

In other words, a simple call like browser.div(visible: true).id will need to check every single div on the page. Large number of elements, means slower execution. The following shows the increasing execution time based on the number of elements on the page:

Executed 10 Times 1 div 10 divs 50 divs 100 divs
browser.div.id 0.966645 1.011956 0.943130 0.931430
browser.div(visible: true).id 1.107269 2.511261 8.877038 17.534622

You may want to consider:

  • Only using :visible when necessary – ie as a tie-breaker for a locator that matches both a visible and hidden element.
  • When using :visible, use other locators to limit the potential matches (wire calls).

Does not change interaction rules

Note that this is just a locator. It does not change the fact that the element is hidden and therefore cannot be interacted with.

browser.div(visible: false).click
#=> C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/elements/element.rb:528:in `rescue in wait_for_present': element located, but timed out after 30 seconds, waiting for true condition on {:visible=>false, :tag_name=>"div"} (Watir::Exception::UnknownObjectException)
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/elements/element.rb:518:in `wait_for_present'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/elements/element.rb:535:in `wait_for_enabled'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/elements/element.rb:658:in `element_call'
#=>   from C:/Ruby23/lib/ruby/gems/2.3.0/gems/watir-6.0.2/lib/watir/elements/element.rb:114:in `click'
#=>   from watir-webdriver.rb:99:in `<main>'
Advertisements
Posted in Watir | Tagged , | 7 Comments

ParallelTests::RSpec::RuntimeLogger ignores first process

Problem

Inspired by a recent meeting with the team at Loblaws Digital, I have been looking at tools to improve the execution of my regression suite. To address an ever growing execution time, I turned to the ParallelTests gem. This gem offered the ability to group RSpec examples, which could then be run in parallel on multiple machines.

Using the default grouping by file size, resulted in a huge disparity in processing times. One machine finished in an hour, while another took almost 2 hours. Not particularly surprising given that these are UI tests.

There is an option to group tests by runtime. For this, ParallelTests needs a runtime history for each spec file. This can be generated by using the ParallelTests::RSpec::RuntimeLogger:

parallel_rspec spec -o "--format ParallelTests::RSpec::RuntimeLogger --out tmp/parallel_runtime_rspec.log"

Unfortunately, this produces an empty log when using a single process. With multiple processes, test times were logged, but not for the first process. What is going on? How do we get the run times for the first (or only) process?

Solution

Digging into the ParallelTests::RSpec::RuntimeLogger, you can see that the log file is written by:

def start_dump(*args)
  return unless ENV['TEST_ENV_NUMBER'] #only record when running in parallel
  # TODO: Figure out why sometimes time can be less than 0
  lock_output do
    @example_times.each do |file, time|
      relative_path = file.sub(/^#{Regexp.escape Dir.pwd}\//,'').sub(/^\.\//, "")
      @output.puts "#{relative_path}:#{time > 0 ? time : 0}"
    end
  end
  @output.flush
end

Inspecting the ENV['TEST_ENV_NUMBER'] you will get “nil” for the first process and “2” for the second process. Due to the “nil”, the first line’s return will execute, skipping the logging. I do not understand why you would ever want to use this formatter and skip logging, but fine, let’s ignore that. Where does the ENV['TEST_ENV_NUMBER'] get set?

Looking through the repository, you can see the ParallelTests::Test::Runner.execute_command creates a set of values for later use as environment variables:

def execute_command(cmd, process_number, num_processes, options)
  env = (options[:env] || {}).merge(
    "TEST_ENV_NUMBER" => test_env_number(process_number, options),
    "PARALLEL_TEST_GROUPS" => num_processes
  )
  cmd = "nice #{cmd}" if options[:nice]
  cmd = "#{cmd} 2>&1" if options[:combine_stderr]
  puts cmd if options[:verbose]

  execute_command_and_capture_output(env, cmd, options[:serialize_stdout])
end

More importantly, the TEST_ENV_NUMBER value is defined by:

def test_env_number(process_number, options={})
  if process_number == 0 && !options[:first_is_1]
    ''
  else
    process_number + 1
  end
end

For the first process, an empty String is returned. When it gets used in execute_command_and_capture_output, the setting of the environment variable is done with:

"(SET \"#{k}=#{v}\")"

Note this means the environment variable is set using SET TEST_ENV_NUMBER= not SET TEST_ENV_NUMBER="". This is why ENV['TEST_ENV_NUMBER'] is “nil”.

The next question is what is the options[:first_is_1]? Can we set that value so that test_env_number returns the process_number + 1 instead? This takes us to the ParallelTests::CLI. Here we can see that the option is set to true when using the “–first-is-1” flag.

In the end, this long stroll through the code tells us that we can fix the logging by running:

parallel_rspec spec --first-is-1 -o "--format ParallelTests::RSpec::RuntimeLogger --out tmp/parallel_runtime_rspec.log"
Posted in RSpec | Tagged | 1 Comment

Finding the next empty text field

Problem

As I continued to investigate making Watir-Classic tests compatible with Watir-Webdriver, I noticed one test that failed to input the next empty row of a text field grid. The grid could start empty or it could start with rows pre-populated with saved values:

<html>
  <body>
    <table>
      <tr>
        <td><input type="text" id="name_01" value="existing name"></td>
        <td><input type="text" id="value_01" value="existing value"></td>
      </tr>
      <tr>
        <td><input type="text" id="name_02"></td>
        <td><input type="text" id="value_02"></td>
      </tr>
      <tr>
        <td><input type="text" id="name_03"></td>
        <td><input type="text" id="value_03"></td>
      </tr>      
    </table>
  </body>
</html>

The test looked for the first row with an empty field and inputted it, repeating if multiple rows of data were needed. The Watir-Classic code boiled down to:

next_field = browser.text_field(id: /name/, value: '')
p next_field.id
#=> "name_02"

next_field.set('some text')
next_field = browser.text_field(id: /name/, value: '')
p next_field.id
#=> "name_03"

Sadly, the same code failed with Watir (previously named Watir-Webdriver):

next_field = browser.text_field(id: /name/, value: '')
p next_field.id
#=> unable to locate element, using {:id=>/name/, :value=>"", :tag_name=>"input or textarea", :type=>"(any text type)"} (Watir::Exception::UnknownObjectException)

Solution

The problem is that Watir’s XPath builder will look for an element that has the value attribute with an empty string value. Unfortunately, that is not the same as our element, which does not have any value attribute. We could address this by writing our own XPath locator that checks for the absence of the value attribute (or wait for the functionality to be added to Watir in Issue 345):

next_field = browser.text_field(xpath: './/input[@type="text"][not(@value)]')
p next_field.id
#=> "name_02"

next_field.set('some text')
next_field = browser.text_field(xpath: './/input[@type="text"][not(@value)]')
p next_field.id
#=> "name_02"

This only works for the first row after the pre-populated rows. As seen by the attempt to input the second blank row, Watir grabs the same row, which is no longer empty. I recently learned on Stack Overflow from Tom Walpole, that this is due to the value property being set by the set method, but not the value attribute. Selenium-WebDriver only checks the attribute, which as we have not changed, results in the same row being returned each time.

Another option would be to exploit the fact that Watir will check the value property when it cannot build an XPath expression. Locators using non-trivial regular expressions, such as that for our empty string /^$/, will trigger this behaviour.

next_field = browser.text_field(id: /name/, value: /^$/)
p next_field.id
#=> "name_02"

next_field.set('some text')
next_field = browser.text_field(id: /name/, value: /^$/)
p next_field.id
#=> "name_03"

As you can see, we got the desired result. Note that this may break in future releases. Finding ways to convert regular expressions into XPath provides an improvement boost in locators. While Watir currently only optimizes a couple of scenarios, there is the possibility that more will be done. Those changes could result in the above code once again checking the value property. If you want to avoid that risk, you may want to explicitly check the property:

next_field = browser.text_fields(id: /name/).find { |t| t.value.empty? }
p next_field.id
#=> "name_02"

next_field.set('some text')
next_field = browser.text_fields(id: /name/).find { |t| t.value.empty? }
p next_field.id
#=> "name_03"
Posted in Watir, Watir Migration, Watir-Webdriver | Tagged , , | Leave a comment

Replace Table#row_count and Table#column_count with an ElementCollection#count

Given a table:

<table>
  <tr>
    <td>Row 1 - Column 1</td>
    <td>Row 1 - Column 2</td>
  </tr>
  <tr>
    <td>Row 2 - Column 1</td>
    <td>Row 2 - Column 2</td>
  </tr>
  <tr>
    <td>Row 3 - Column 1</td>
    <td>Row 3 - Column 2</td>
  </tr>
</table>

You might want to check the number of rows and/or columns.

Obsolete Method

In Watir-Classic you may have retrieved these values using the row_count and column_count methods.

browser.table.row_count
#=> 3
 
browser.table.column_count
#=> 2

However, these methods will give an error in Watir-Webdriver:

browser.table.row_count
#=> NoMethodError
 
browser.table.column_count
#=> NoMethodError

Preferred Method

For Watir-Webdriver, you will need to count the tr and td elements using an elemnent collection:

browser.table.trs.count
#=> 3
 
browser.table.tr.tds.count
#=> 2

Note that this will return all tr and td elements in the table. Watir-Classic’s method ignored the nested tables, therefore, for nested tables, the equivalent Watir-Webdriver method will need to use the rows and cells methods:

browser.table.rows.count
#=> 3
 
browser.table.row.cells.count
#=> 2
Posted in Watir, Watir Migration, Watir-Classic | Leave a comment

Watir 6.0 is the end of the Watir metagem

The Watir gem started out as driver for IE through the OLE protocol. In 2012, version 4.0.0 changed Watir into a metagem that, based on the desired browser, used either Watir-Classic (the original implementation) or Watir-Webdriver (the Selenium backed implementation that supported additional browsers). The soon to be released Watir 6.0 will continue the evolution to being just Watir-Webdriver.

You can find out more about Watir 6.0 from:

What does this mean for Watir-Classic users?

Anyone using:

require 'watir'

Must update to using:

require 'watir-classic'

This is another reminder that support for Watir-Classic is limited. If possible, you should switch to Watir-Webdriver.

What does this mean for Watir-Webdriver users?

Anyone using:

require 'watir-webdriver'

Will get a deprecation warning unless they switch to:

require 'watir'

The default browser will be changed from Firefox to Chrome. This means that anyone using the default browser to start Firefox:

browser = Watir::Browser.new 

Will now need to explicitly specify Firefox:

browser = Watir::Browser.new :firefox
Posted in Watir, Watir-Classic, Watir-Webdriver | Leave a comment

Toggle a checkbox

Problem

Checking a checkbox is as simple as:

browser.checkbox.set

Clearing a checkbox is just as easy:

browser.checkbox.clear

What if you want to toggle the state of the checkbox – ie check it if its unchecked or uncheck it if it is checked?

Solution

The set? method returns the current state of the checkbox, therefore the negation is the state of the checkbox once toggled:

browser.checkbox.set?
#=> true
!browser.checkbox.set?
#=> false

We could write an if statement based on the set? method. However, we can find a simpler solution by passing a parameter to the set:

  • true – sets the checkbox
  • false – clears the checkbox

Putting it all together, we can toggle the checkbox by:

checkbox = browser.checkbox
checkbox.set(!checkbox.set?)
Posted in Watir, Watir-Classic, Watir-Webdriver | Tagged | 16 Comments

Unhiding the overflow:hidden in DevExtreme select lists

Problem

When Dev Silver asked me how to automate a DevExtreme select list, it seemed like a simple task. It looked like any other set of elements styled as a select list.

# Go to the page
browser = Watir::Browser.new
browser.goto('js.devexpress.com/Demos/WidgetsGallery/#demo/editors-select_box-overview')
iframe = browser.iframe(id: 'demo-frame')

# Find the dropdown
dropdown = iframe.div(id: 'products-simple')
dropdown.wait_until_present

# Open the list of dropdown options
dropdown.div(class: 'dx-dropdowneditor-button').click
list_container = iframe.div(class: 'dx-dropdownlist-popup-wrapper').div(class: 'dx-scrollable-container')
list_container.wait_until_present

# Click a list item
list_container.div(text: 'SuperLED 50').click

It worked! Well… at least for some options. Clicking some of the other options resulted in an exception:

list_container.div(text: 'Projector Plus').click
#=> Selenium::WebDriver::Error::ElementNotVisibleError

What was going on?

Solution

After investigating the DevExtreme HTML, I was able to narrow the problematic HTML to the following:

<div style="overflow:hidden; height:59px; width:200px; border:1px solid black;" class="dx-scrollable-container">
  <div style="line-height:20px" class="dx-list-item">HD Video Player</div>
  <div style="line-height:20px" class="dx-list-item">SuperPlasma 50</div>
  <div style="line-height:20px" class="dx-list-item">SuperLED 50</div>
  <div style="line-height:20px" class="dx-list-item">Projector Plus</div>
  <div style="line-height:20px" class="dx-list-item">ExcelRemote IR</div>
</div>

Which gets rendered as:

HD Video Player
SuperPlasma 50
SuperLED 50
Projector Plus
ExcelRemote IR

 

Notice that the outer div element has a style of overflow:hidden. This means that any content that does not fit within the element’s dimensions will be hidden to the user. There is no scrollbar for the user to see the hidden content. In other words, a user can see the first 3 list items, but not the last 2. WebDriver mimics the user – it can only see and click the first 3 items. The last 2 items are not visible and therefore cannot be interacted with.

browser.divs(class: 'dx-list-item').map(&:visible?)
#=> [true, true, true, false, false]

To interact with the overflowed/hidden items, they must first be made visible. The actual DevExtreme control does provide another element that mimics the scrollbar behaviour. However, with the control relying on mouseovers, it seemed a nuisance to automate. Instead, I chose to mimic the scrolling via a JQuery script written by James on StackOverflow:

list_item = list_container.div(text: 'Projector Plus')
script = '$(arguments[0]).scrollTop($(arguments[1]).offset().top - $(arguments[0]).offset().top + $(arguments[0]).scrollTop());'
iframe.execute_script(script, list_container, list_item)
list_item.click
Posted in Watir, Watir-Webdriver | Tagged , | 2 Comments