34

If I've got some HTML like:

<div id='drawer'><ul><li><a href='www'>description</a>...

I've seen that I can get the value of href in Capybara with:

page.find('div#drawer a')['href']

But is there any way to retrieve that value if it's completely described as a css string? ie, trying to get the value for 'div#drawer a[href]'

I've tried with expressions like this:

page.find('div#drawer a[href]')        => can't convert Capybara::Node::Element into String (TypeError)
page.find('div#drawer a[href]').value  => can't convert nil into String (TypeError)
page.find('div#drawer a[href]').text   => returns the text value of 'description'

I've got that css expression in an external config file, so would it be possible somehow to just use it directly and retrieve the value of the attribute in question?

Thank you...

mickael
  • 2,033
  • 7
  • 25
  • 38
  • `a[href]` is just a selector that matches all `a` elements that have a `href` attribute. What do you mean by "described as a CSS string"? – Blender Dec 17 '12 at 00:51
  • @Blender, I meant that `div#drawer a[href]` is a string that was trying to described the attribute that was required with CSS syntax. But maybe this is not possible then? @Andrey, I was experimenting with the possibility to put the required CSS descriptions of all page elements in external JSON files so that I could change that single point of configuration in the future in case of any modification. Right now, the elements are identify individually in each step, so if something changes, you'll need to amend quite a lot of different files... – mickael Dec 17 '12 at 19:31

3 Answers3

75

Probably too late. But I also had the same problem and found the solution. It might help someone else.

page.find('div#drawer a')[:href]
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Leonardo Alves
  • 1,876
  • 1
  • 16
  • 19
3

The only way I have been able to do this is with jQuery.

href = page.evaluate_script("$('a.link_class').attr('href');")
Josh Kovach
  • 7,679
  • 3
  • 45
  • 62
RobertH
  • 528
  • 3
  • 13
2

If you are looking for an HTML element with a given value for a given attribute, you could do:

expect(page).to have_css('a[href="www"]')
cdmo
  • 1,239
  • 2
  • 14
  • 31