user1523236
user1523236

Reputation: 1463

click element if it exists in 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.

Upvotes: 20

Views: 24642

Answers (4)

Fangxing
Fangxing

Reputation: 6115

You can use first, with option minimum: 0

item = first ".dropdown-item", minimum: 0
item.click if item&.visible?

Upvotes: 2

Wojtek Kostański
Wojtek Kostański

Reputation: 311

In case I used has_css? query :

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

Upvotes: 13

Andrei Botalov
Andrei Botalov

Reputation: 21096

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.

Upvotes: 33

Whitney Imura
Whitney Imura

Reputation: 810

Have you tried doing 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

Upvotes: -4

Related Questions