Search code examples
rubytestingwatir

How to skip an element when iterating through a list Ruby


I have the following script which loops through an element list:

  $browser.divs(class:'menu-index-page__menu-category').map do |cat|
  cate = cat.h3.text
  puts cate

  cc = cat.ul(class:'menu-index-page__items')
  cc.lis(class:'menu-index-page__item').each do |lit|
    lit.fire_event :click
    sleep(5)

Once in a while the name of the class list changes to:

menu-index-page__item menu-index-page__item--unavailable

This breaks the script, and I want to be able to skip this whenever it comes up and continue with the original script.

enter image description here


Solution

  • Assuming that you are using Watir v6.5+, the :class locator supports excluding classes. You can find all elements that include class "a", but not "b" by doing:

    browser.elements(class: ['a', '!b'])
    

    For your specific example, you can do:

    cc.lis(class: ['menu-index-page__item', '!menu-index-page__item--unavailable']).each do |lit|
      # your actions on lit
    end