John Dow
John Dow

Reputation: 1521

How to click on image as a link using RSpec and Capybara

I'm using Rspec and Capybara.

How can I write a step to click on an image? I have been unable to find a good way to get Capybara to see the image as a link.

Thanks

Example of html

<a title="inGroups" href="/de/users/index/roles-list/serviceID/1112/inGroup/1">
  <img border="0" alt="inGroups" src="/themes/system/images/icon/16/role_activate.png">

<a title="inGroups" href="/de/users/index/roles-list/serviceID/1114/inGroup/1">
   <img border="0" alt="inGroups" src="/themes/system/images/icon/16/role_activate.png">

<a title="notInGroups" href="/de/users/index/roles-list/serviceID/1112/inGroup/0">
   <img border="0" alt="notInGroups" src="/themes/system/images/icon/16/role_deactivate.png">

<a title="notInGroups" href="/de/users/index/roles-list/serviceID/1114/inGroup/0">
    <img border="0" alt="notInGroups" src="/themes/system/images/icon/16/role_deactivate.png">

Any suggestions?

Upvotes: 2

Views: 5164

Answers (2)

rld
rld

Reputation: 2763

I put this and works: for the index.html got to the show:

 find("img[src*='photo03.jpg']").click

for the show.html

expect(page).to have_css("img[src*='photo03.jpg']")

Upvotes: 0

Jon M
Jon M

Reputation: 11705

It shouldn't be any different to clicking a normal link. I don't see how you would go about selecting an individual link in your example though, without any uniquely identifiable attributes on the link.

If you can't change the markup, you may need to use XPath to actually select the href element by the URL e.g.

my_link = find(:xpath, "//a[contains(@href,'1114/inGroup/1')]")

Would give you the first link, and then

my_link.click

Should click it as normal.

EDIT: Just to clarify, the important thing is that you select the a element and click it, not the img.

Upvotes: 9

Related Questions