Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show a diff for comparisons of arrays of one-line strings #597

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions lib/rspec/support/differ.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ class Differ
def diff(actual, expected)
diff = ""

unless actual.nil? || expected.nil?
unless actual.nil? || expected.nil? || pointless_diff?(actual, expected)
if all_strings?(actual, expected)
if any_multiline_strings?(actual, expected)
diff = diff_as_string(coerce_to_string(actual), coerce_to_string(expected))
end
diff = diff_as_string(coerce_to_string(actual), coerce_to_string(expected))
elsif no_procs?(actual, expected) && no_numbers?(actual, expected)
diff = diff_as_object(actual, expected)
end
Expand Down Expand Up @@ -81,8 +79,8 @@ def all_strings?(*args)
safely_flatten(args).all? { |a| String === a }
end

def any_multiline_strings?(*args)
all_strings?(*args) && safely_flatten(args).any? { |a| multiline?(a) }
def pointless_diff?(actual, expected)
String === actual && String === expected && !multiline?(actual) && !multiline?(expected)
end

def no_numbers?(*args)
Expand Down
30 changes: 30 additions & 0 deletions spec/rspec/support/differ_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,36 @@ module Support
expect { differ.diff(actual, expected) }.not_to change { differ_ivars }
end

it 'returns the expected diff for arrays of single-line strings' do
expected = ["foo"]
actual = ["foo", "bar"]

expected_diff = dedent(<<-'EOS')
|
|@@ -1,2 +1,3 @@
| foo
|+bar
|
EOS
diff = differ.diff(actual, expected)
expect(diff).to eq(expected_diff)
end

it 'does not give an empty string for single-element arrays of single-line strings' do
expected = ["foo"]
actual = ["bar"]

expected_diff = dedent(<<-'EOS')
|
|@@ -1 +1 @@
|-foo
|+bar
|
EOS
diff = differ.diff(actual, expected)
expect(diff).to eq(expected_diff)
end

def differ_ivars
Hash[ differ.instance_variables.map do |ivar|
[ivar, differ.instance_variable_get(ivar)]
Expand Down
Loading