[rspec-users] Windowed comparison for differences in the middle of long strings

Alex Chaffee alexch at gmail.com
Wed Jul 14 15:15:47 EDT 2010

When two strings fail to match, if the difference is somewhere in the
middle of the strings, it can be annoying/impossible to track down the
actual difference. I've written a little Comparison object that
provides this kind of error message:

Strings differ at position 12:
expected: ..."efghijklmnopqrst"...
actual: ..."efghijklXnopqrst"...

It shows a "prelude" of a few characters, then the difference, on
successive lines so they're easy to visually scan. It also does the
right thing (or tries to) if the difference is near the beginning or
end of the string (i.e. does or doesn't show ellipses).


For people who can't wait for this to get incorporated into RSpec
proper, you can require comparison.rb and it'll override the existing
RSpec == matcher. Or wait for http://github.com/rspec/rspec-expectations/issues/issue/9
to be pulled into version 2.1 (maybe).

One open question is whether the exception message should show the
full actual string as well as the comparison... On one hand, it adds
to screen clutter, but on the other hand, it can be important in
tracking down the problem, especially if the prelude is ambiguous.

More information about the rspec-users mailing list