Skip to content

Commit

Permalink
Extend matcher protocol to support custom differs
Browse files Browse the repository at this point in the history
  • Loading branch information
sponomarev committed Jan 16, 2019
1 parent 959b859 commit 547fa8a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/rspec/expectations/fail_with.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ def fail_with(message, matcher=nil)
end

message = if !matcher.nil?
::RSpec::Matchers::ExpectedsForMultipleDiffs.from(matcher.expected).message_with_diff(message, differ, matcher.actual)
else
::RSpec::Matchers::ExpectedsForMultipleDiffs.from(nil).message_with_diff(message, differ, nil)
end
differ_in_use = matcher.respond_to?(:differ) ? matcher.differ : differ

::RSpec::Matchers::ExpectedsForMultipleDiffs.from(matcher.expected).message_with_diff(message, differ_in_use, matcher.actual)
else
::RSpec::Matchers::ExpectedsForMultipleDiffs.from(nil).message_with_diff(message, differ, nil)
end

RSpec::Support.notify_failure(RSpec::Expectations::ExpectationNotMetError.new message)
end
Expand Down
7 changes: 7 additions & 0 deletions lib/rspec/matchers/matcher_protocol.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ class MatcherProtocol
# and that the values returned by these can be usefully diffed, which can
# be included in the output.

# @!method differ
# @return [Object] An `RSpec::Support::Differ` compatible object.
# Provides a custom differ object to calculate printable difference
# between `actual` and `expected` attributes. The result will be
# included in the output. `diffable?` should be defined as well to make
# it work.

# @!method actual
# @return [String, Object] If an object (rather than a string) is provided,
# RSpec will use the `pp` library to convert it to multi-line output in
Expand Down
18 changes: 18 additions & 0 deletions spec/rspec/expectations/fail_with_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,24 @@
RSpec::Expectations.fail_with "message", matcher_class.new(expected, actual)
}.to fail_with("message\nDiff:#{expected_diff}")
end

context "when matcher provides custom differ" do
let(:custom_differ) { double("custom differ") }
let(:custom_diff) { "custom diff" }
let(:matcher_class) { Struct.new(:expected, :actual, :differ) }

before(:example) do
allow(custom_differ).to receive(:diff).and_return(custom_diff)
end

it "uses custom differ instead of default" do
expect(RSpec::Expectations).not_to receive(:differ)

expect {
RSpec::Expectations.fail_with "message", matcher_class.new("abc", "def", custom_differ)
}.to fail_with("message\nDiff:#{custom_diff}")
end
end
end

RSpec.describe RSpec::Expectations, "#fail_with with --color" do
Expand Down

0 comments on commit 547fa8a

Please sign in to comment.