Question

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!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top