-
-
Save crafterm/183443 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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