Josh Johnson
Josh Johnson

Reputation: 563

Clicking on image using Capybara in cucumber

I am attempting to click an image with Capybara for a Cucumber test, but cannot find a way to get Capybara to see the image as a link.

My code for the image is:

link_to(image_tag('ico_edit_16.png', alt: 'Edit', class: 'icon16', title: "Edit #{qualification.title}"), edit_qualification_path(qualification))

Which shows up as

<a href="/qualifications/1/edit">
    <img class="icon16" title="Title" src="/images/ico_edit_16.png?1279303992" alt="Edit">
</a>

in the html, and I have been unable to find a good way to use capybara to click the image.

Any suggestions?

Upvotes: 9

Views: 12813

Answers (5)

Andy Waite
Andy Waite

Reputation: 11076

This should work:

find('img.icon16').click

Alternatively to lookup based on the alt text:

find("img[alt='Edit']").click

Upvotes: 13

Heriberto Maga&#241;a
Heriberto Maga&#241;a

Reputation: 898

yeah if you are using something like in my case in haml:

%div{id: "23", class: 'operations'}
  %a.delete{ href: '#', class: 'smallbtn'}
    %img{ src: 'assets/delete.png', alt: 'Delete'}

 %a.edit{ href: "#", class: 'smallbtn'}
   %img{ src: 'assets/edit.png', alt: 'Editar Producto'}

and you don't want to use the id to click the link and you are using images, for example in my case to click on delete link you need to declare a class and later you can use the next code to click on the element and additionally to confirm a modal operation:

  within '#23' do
    find('.delete').click
    page.driver.browser.switch_to.alert.accept
  end

Upvotes: 0

user1158559
user1158559

Reputation: 1954

This step solves the problem for me. You have to use xpaths to match an element then find its parent. A caveat, though, is that this might not be synchronized:

When /^I follow the link containing(?:| an| a| the|) "([^\"])" image(?:| within "([^\"])")$/

do |*args|
  alt = args[0] ; within = args[1]

  outer = find(within)
  outer.find(:xpath, "//img[@alt='#{alt}']/..").click
end

Upvotes: 1

Dev S
Dev S

Reputation: 413

I had a problem when the image was not recognized because there were multiple elements hidden in the page with the same id. Try using something like this.

with_scope("#modal_window") do
  find("#close").click

Upvotes: 1

adarsh
adarsh

Reputation: 396

Also note, in Rails (3.1.1 in my case), for images without a given :alt value, a default alt is set by the image_tag helper:

:alt - If no alt text is given, the file name part of the source is used (capitalized and without the extension) [From the Rails API]

So for example, for image file "kitten.jpg", you would use find("img[@alt='Kitten']").click (note capitalization and removal of extension).

Using this rails convention, you can search for arbitrary image links in cucumber/capybara.

Upvotes: 0

Related Questions