Cucumber step to match table rows with Capybara (within wrapper method supported)

Posted . Visible to the public.

Here is an update from the original card to support Capybara's within method.
The original card always looked thru all tables on the page.

The 2 points i changed were :

  • to use Capybara's all method instead of using Nokogiri directly
  • and to use Capybara's node.text method instead of Nokogiri's node.content method

And finally here is the code :

Then /^I should( not)? see the following table rows?( in any order)?:?$/ do |negate, unordered, expected_table|
  expectation = negate ? :should_not : :should
  rows = all(:xpath, './/tr').collect { |row| row.all(:xpath, './/th|td') }
  expected_table = if expected_table.is_a?(String)
    # multiline string. split it assuming a format like cucumber tables have.
    expected_table.split(/\n/).collect do |line|
      line.sub!(/^\|/, '')
      line.sub!(/\|$/, '')
      line.split(/\s*\|\s*/)
    end
  else
    # vanilla cucumber table.
    expected_table.raw
  end
  expected_table.all? do |expected_row|
    first_row = rows.find_index do |row|
      expected_row.all? do |expected_column|
        first_column = row.find_index do |column|
          content = column.text.gsub(/[\r\n\t]+/, ' ').gsub(/[ ]+/, ' ').strip
          content.include? expected_column.gsub('  ', ' ').strip
        end
        if first_column.nil?
          false
        else
          row = row[(first_column + 1)..-1]
          true
        end
      end
    end
    if first_row.nil?
      false
    else
      if unordered
        rows.delete_at(first_row)
      else
        rows = rows[(first_row + 1)..-1]
      end
      true
    end
  end.send(expectation, be_true)
end
Profile picture of george .
george .
Last edit
Attachments
Posted by george . to george .'s deck (2012-02-15 16:39)