Assertion (Verify) to Compare Arrays

The following method compares two arrays and gives a user-friendly message on any mismatched elements. I patch this on to Watir in a patch file, in a module called Assertions inside a module called Watir (I require this patch file when running my tests).

#compare two arrays, fail if they don't match
#report the unmatched elements in a readable format
def verify_array(expected_array, actual_array, message = '')
  #array1 - array2 gives an array containing only the differences
  #(elements in array1 not found in array2)
  differences = (expected_array - actual_array)
  #for each difference, find the index of the value that doesn't match, 
  #so you can show both expected and actual
  differences.each do |difference|
    difference_index = expected_array.index(difference)
    failure = "\n#{"="*30}\nDifference at index #{difference_index.to_s}.\n\#line continues
Expected array value: #{difference.to_s}\nActual array value: #{actual_array[difference_index].to_s}"
    message = message + "\n#{failure}"
  end
  verify(expected_array == actual_array, message)
end
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Sep 29, 2008

    Alister Scott says:

    This isn't specifically to do with Watir.
    This isn't specifically to do with Watir.