Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click element if it exists in capybara

Tags:

capybara

I wish to click a popup message that appears on my test app if it is present. I am new to capybara and cant seem to find a way to do this. I have previous experience with watir and if I were doing 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? Note this link will not always appear hence why I wish to have the if statement.

like image 835
user1523236 Avatar asked Jun 05 '13 19:06

user1523236


2 Answers

A straight of the head code is to just invoke a has_link? matcher and then click_link action:

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

But it will be not the fastest solution as Capybara will make two queries to driver to get element: first one in has_link? and the second one in click_link.

A better variant may be to make only one query to get an element:

# 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 I would go with has_link?/click_link implementation as the second variant does't check that element exists only at one place and the third one is too long.

like image 103
Andrei Botalov Avatar answered Oct 05 '22 15:10

Andrei Botalov


In case I used has_css? query :

if page.has_css?("button #popUpButton") 
    click_button(#popUpButton")
end
like image 37
Wojtek Kostański Avatar answered Oct 05 '22 13:10

Wojtek Kostański