bumpkin
bumpkin

Reputation: 3469

Capybara - check for the existence of a data attribute on a link

I have a link with a specific attribute on my page. Using Rspec + Capybara how can I check for the existence of this link?

<a href="#" id="text" data-content="This is a discrete bar chart.">Foo</a>

Does not work:

page.find(:css, 'a[data-content="This is a discrete bar chart."]')

Works:

page.find(:css, 'a#test')

Upvotes: 12

Views: 12433

Answers (4)

konyak
konyak

Reputation: 11706

Here are some different ways:

expect(page).to have_selector("a[href='#'][data-content='This is a discrete bar chart.']")

page.has_selector?("a[href='#'][data-content='This is a discrete bar chart.']")

page.find("a[href='#'][data-content='This is a discrete bar chart.']")  # returns the node found

If you don't have access to page but have access to rendered, then

expect(Capybara.string(rendered)).to have_selector("a[href='#'][data-content='This is a discrete bar chart.']")

Upvotes: 3

Jon Kern
Jon Kern

Reputation: 3235

This worked for me when searching for a link's title attribute (tooltip):

Then(/^I should see tooltip "(.*?)" on link "(.*?)"$/) do |tip, link|
  within('#results') do
    link = find(:link, link)
    expect(link['title']).to eql(tip)
  end
end

NOTE: the within is optional and useful for reducing chances of ambiguity.

HTML Source code:

<a title="Owner: lfco Fire Department" href="/water_supplies/597df82566e76cfcae000018">Hydrant LFCO One</a>

Upvotes: 0

Armando
Armando

Reputation: 940

I have the same query, but the quotes are different.

find("a[data-method='delete']").click

and works for me.

Upvotes: 14

Joe Susnick
Joe Susnick

Reputation: 6772

It could be an issue of Capybara finding too many results. Maybe change 'find' to 'all' and see if you get an array of results that you could select from. Best of luck.

Upvotes: 1

Related Questions