Fandratt Muda
Fandratt Muda

Reputation: 140

Can Not Click The Same Element Class Using Watir

I have the following screen: enter image description here And I use the following Ruby script to click the "Add New" button:

vendorTab = driver.a id: "tab-master-tab-vendor"
  vendorTab.wait_until_present
  if vendorTab.exists?
    vendorTab.click
  end

  addNewButton = driver.button class: ['btn btn-primary']
  addNewButton.wait_until_present
  if addNewButton.exists?
      addNewButton.click
  end

But, when I move to another tab and try to click the same "Add New" button, the Ruby script doesn't work. enter image description here Is there anything wrong with my Ruby code?

buildingTypeTab = driver.a id: "tab-master-tab-building"
buildingTypeTab.wait_until_present
if buildingTypeTab.exists?
  buildingTypeTab.click
end

  addNewButton = driver.button class: ['btn btn-primary']
  addNewButton.wait_until_present
  if addNewButton.exists?
      addNewButton.click
  end

I Appreciate your help. Thank you very much.

Upvotes: 1

Views: 239

Answers (2)

Fandratt Muda
Fandratt Muda

Reputation: 140

After reading the suggestions from pjd, I modified it a bit and got it working like this:

buildingTypeTab = driver.a id: "tab-master-tab-building"
buildingTypeTab.wait_until_present
if buildingTypeTab.exists?
  buildingTypeTab.click
end

  addNewButton = driver.button(:class => ['btn btn-primary'], :index => 2)
  addNewButton.wait_until_present
  if addNewButton.exists?
      addNewButton.click
  end

As pjd said, yes all these tabs are part of the same HTML

Thank you.

Upvotes: 0

pjd
pjd

Reputation: 1173

I guess all of these tabs are part of the same web page? I.e., all in the same HTML?

If that is the case, driver.button class: ['btn btn-primary'] is going to stop when it finds the first instance in the HTML, but that isn't the button you are looking for every time (it's the button in the first tab, where your script worked as you expected).

The best options in my mind are

  • find a way to uniquely identify the button in each tab (for example, use id instead of class if possible), or
  • pull all the buttons into a collection and click the button using its collection index after you figure out which index aligns with each tab. For example,

button_collection = browser.buttons(:class, ['btn', 'btn-primary']) button_collection[2].click # Will click the 3rd button in the collection

Upvotes: 3

Related Questions