Click element if it exists in capybara

I want to click the pop-up message that appears in my test application, if present. I am new to capybara and cannot find a way to do this. I have previous experience with watir, and if I did it with watir, it would be something like:

if browser.link(:text, "name").exists? do browser.link(:text, "name").click end 

How can i do the same in capybara? Please note: this link does not always appear, so I want to have an if statement.

+7
source share
3 answers

You tried to do something like:

 if page.find('.id') do click_link('Some Link') # or page.find('.id').click else page.should_not have_selector('.id') # or something like that end 
-3
source

The direct code for the chapter is to simply call has_link? and then click_link action:

 if page.has_link?('name') page.click_link('name') end 

But this will not be the fastest solution, since Capybara will make two requests for the driver to get the item: first one in has_link? , and the second in click_link .

The best option would be to create only one request to get the item:

 # This code doesn't check that an element exists only at one place and just chooses the first one link = first('name') link.click if link 

or

 # This code checks that element exists only at one place links = all('name') unless links.empty? links.count.should == 1 link = links.first link.click end 

Personally, would I go with the has_link? implementation has_link? / click_link , since the second option does not verify that the element exists in only one place, and the third is too long.

+22
source

In case I used the has_css? request has_css? :

 if page.has_css?("button #popUpButton") click_button(#popUpButton") end 
-one
source

All Articles