2

I know that /Interface \d/ occurs three times on the page. But I don't know how to test for this with Capybara in Cucumber. Here was my first attempt:

Then /^(?:|I )should see \/([^\/]*)\/ (\d+)(?:x|X| times?)?$/ do |regexp, count|
  regexp = Regexp.new(regexp)
  count = count.to_i
  if page.respond_to? :should
    page.should have_xpath('//*', { :text => regexp, :count => count })
  else
    assert page.has_xpath?('//*', { :text => regexp, :count => count })
  end
end

However, this returns false for my Then I should see /Interface \d+/ 3 times.

I figured out that this is because has_xpath uses all. Putting this in my test:

puts all(:xpath, '//*', { :text => regexp}).map {|e| pp e}

results in

#<Capybara::Element tag="html" path="/html">
#<Capybara::Element tag="body" path="/html/body">
#<Capybara::Element tag="div" path="/html/body/div">
#<Capybara::Element tag="div" path="/html/body/div/div[2]">
#<Capybara::Element tag="table" path="/html/body/div/div[2]/table">
#<Capybara::Element tag="tbody" path="/html/body/div/div[2]/table/tbody">
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[1]">
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[1]/td[3]">
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[2]">
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[2]/td[3]">
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[3]">
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[3]/td[3]">

So I am getting a count of every step along the way to the elements that contain my text. :-\

I thought maybe has_content would save me, but it doesn't accept a count.

Help!

chadoh
  • 4,343
  • 6
  • 39
  • 64

1 Answers1

2

Something like this should work:

Then /^(?:|I )should see \/([^\/]*)\/ (\d+)(?:x|X| times?)?$/ do |regexp, count|
  regexp = Regexp.new(regexp)
  count = count.to_i
  page.find(:xpath, '//body').text.split(regexp).length.should == count+1
end
Zubin
  • 9,422
  • 7
  • 48
  • 52
  • Two reasons I don't like to use "within blah": 1) It's brittle. Right now these are in s, but that will change soon. I don't want to have to change the test. 2) It's not really from a user-perspective, which I like to try to stick to as much as possible in cucumber features. – chadoh Nov 22 '10 at 13:50
  • Fair enough... I've removed the css selector suggestion. – Zubin Nov 27 '10 at 19:05