Maycon Silva
Maycon Silva

Reputation: 1

How to iterate with more than one element on the page

I have several buttons to click on the same page. How do I iterate and click on each of them?

def btnConectar()


   elements = all("button[data-control-name='srp_profile_actions']").count 

    puts elements

    first("button[data-control-name='srp_profile_actions']").click 
    find("section[class=modal]")
    find("button[class='button-primary-large ml1']").click

end

Upvotes: 0

Views: 120

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49890

all returns an Array like Capybara::Result object. You can iterate through that using the standard ruby enumerable methods.

all("button[data-control-name='srp_profile_actions']").each do |el|
  el.click
  find("section[class=modal]") # Not sure what this is for - if it's an expectation/assertion it should be written as such
  click_button(class: %w(button-primary-large ml1) 
end

That will work as long as clicking on the button doesn't cause the browser to move to another page.

If clicking does cause the browser to move to another page then all the rest of the elements in the Capybara::Result object will become stale (resulting in a stale element reference error on the next iteration) and you won't be able to iterate any more. If that is your case then details on what exactly you're doing will be necessary. Questions like does the original button still exist on the page after clicking the button-primary-large button, or can you iterate by just clicking the first matching button over and over? If it does still exist is it changed in any way to indicate it's already been clicked, or is the number/order of buttons on the page guaranteed to be stable? It would probably help to understand if you posted a fragment of the HTML for the first and second iteration.

Upvotes: 1

Maycon Silva
Maycon Silva

Reputation: 1

 def btnConectar()

        page.all("button[data-control-name='srp_profile_actions']").each do |el|

        while page.has_css?("button[data-control-name='srp_profile_actions']")  

        el.click #Click the button
        find("section[class=modal]") #Modal mapping
        click_button(class: %w(button-primary-large ml1)) #Click the button
        sleep 3

        end

    end

end

Upvotes: 0

Related Questions