Search code examples
arraysrubyrspecdiffmatcher

Enable diffing for RSpec array matcher


RSpec provides a "diff"-style output when comparing multi-line strings. Is there a way to do something similar when comparing arrays (other than converting the array to a multi-line string)?


Solution

  • I may be mistaken, but I don't think this feature is built-in to RSpec.

    However, you could implement a custom matcher with a custom error message:

    RSpec::Matchers.define(:eq_array) do |expected|
      match { |actual| expected == actual }
    
      failure_message do |actual|
        <<~MESSAGE
          expected: #{expected}
          got:      #{actual}
    
          diff:     #{Diffy::Diff.new(expected.to_s, actual.to_s).to_s(:color)}
        MESSAGE
      end
    end
    
    # Usage:
    
    expect([1, 2, 3]).to eq_array([1, 4, 3])
    

    This demo is using the diffy library; you could implement this however you see fit.