简体   繁体   中英

How to find a tag using XPath and click it using Capybara

What is the best way to find the element and click in my automation project, using Ruby, Capybara, Selenium, Cucumber, XPath, etc.

The HTML element I need to click and expand (equal accordion) is:

<a href="javascript:;" class="dcjq-parent">
  <i class=""></i>
  <span>Customs Reports</span>
  <span class="dcjq-icon"></span>
</a>

I currently use the XPath command to find the element and click, but it doesn't work very well because it is finding the element but sometimes clicks and sometimes doesn't.

page.find(:xpath, "//*[text()='Customs Reports']").click

To click a link in Capybara you can use:

click_link 'Customs Reports'

Another way is:

find('span', text: 'Customs Reports').click

As @mechnicov has stated, the "proper" way to click a link is with click_link 'Customs Reports' however it's probably not going to behave any differently than what you're doing.

This is because Capybara will click the link as soon as it "sees" it, which may be before the required JavaScript behavior has been attached, or while the link is being animated into the page (moving).

Either one can produce the flaky behavior you're seeing because the JavaScript behavior won't trigger, or if animating because the click can miss the moving link. You can test that by adding a sleep before the click, but the proper way to fix it is to assert for something on the page that indicates the page is actually ready for user input.

What that assertion would be is completely dependent on the app you're testing and what is actually happening on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM