Clicking on an image using Capybara in cucumbers

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

My code for the image:

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

What is displayed as

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

in html and I could not find a good way to use capybara to click an image.

Any suggestions?

+7
source share
5 answers

This should work:

 find('img.icon16').click 

Alternative to search based on alt text:

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

I had a problem when the image was not recognized, because there were several elements with the same identifier on the page. Try using something like this.

 with_scope("#modal_window") do find("#close").click 
+1
source

This step solves the problem for me. You must use xpaths to match the element, then find its parent. However, the caveat is that this may not be in sync:

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

 do |*args| alt = args[0] ; within = args[1] outer = find(within) outer.find(:xpath, "//img[@alt='#{alt}']/..").click end 
+1
source

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

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

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

Using this rail convention, you can search for arbitrary image references in cucumber / capybara.

0
source

Yes, if you use something like 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 identifier to click the link, and you use images, for example, in my case, to click the delete link that you must declare to the class, and then you can use the following code to click the element and additionally to confirm the modal operation :

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

All Articles