Skip to content

Instantly share code, notes, and snippets.

@crafterm
Forked from cjheath/file_matcher.rb
Created September 9, 2009 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crafterm/183443 to your computer and use it in GitHub Desktop.
Save crafterm/183443 to your computer and use it in GitHub Desktop.
#
# A Custom Matcher for RSpec that shows the difference between two multi-line strings.
# Author: Clifford Heath.
# Usage:
# actual_text.should_not differ_from(expected_text)
#
require 'diff/lcs'
module FileMatcher
class BeDifferent
def initialize(expected)
@expected = expected.scan(/[^\r\n]+/)
end
def matches?(actual)
actual_lines = actual.scan(/[^\r\n]+/)
differences = Diff::LCS::diff(@expected, actual_lines)
@diff = differences.map do |chunk|
added_at = (add = chunk.detect{|d| d.action == '+'}) && add.position+1
removed_at = (remove = chunk.detect{|d| d.action == '-'}) && remove.position+1
"Line #{added_at}/#{removed_at}:\n"+
chunk.map do |change|
"#{change.action} #{change.element}"
end*"\n"
end*"\n"
@diff != ''
end
def failure_message
"expected a difference, but got none"
end
def negative_failure_message
"expected no difference, but got:\n#{@diff}"
end
end
def differ_from(expected)
BeDifferent.new(expected)
end
end
Spec::Runner.configure do |config|
config.include(FileMatcher)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment