Created
July 14, 2020 20:42
-
-
Save benoittgt/9d7c33aca1f9d96e9804bb74aa02dba4 to your computer and use it in GitHub Desktop.
RSpec matcher with block execution
This file contains hidden or 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
begin | |
require "bundler/inline" | |
rescue LoadError => e | |
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" | |
raise e | |
end | |
gemfile(true) do | |
source "https://rubygems.org" | |
gem "rspec" | |
end | |
require 'rspec/autorun' | |
RSpec.configure do |rspec| | |
rspec.default_formatter = 'doc' | |
end | |
# https://twitter.com/kennethmayer/status/1283084667843776515 | |
# Rspec Twitter: Is it possible to write a custom matcher that also yields to a given block? | |
RSpec.describe do | |
RSpec::Matchers.define :match_to_string do |expected| | |
match do |actual| | |
match = true | |
unless actual.to_s == expected.to_s | |
@failure_message_expectation = "expected that #{actual}.to_s would be a eq to #{expected}.to_s. " | |
match = false | |
end | |
unless @matcher_block.call(actual, expected) | |
@failure_message = @failure_message_custom_matcher | |
match = false | |
end | |
match | |
end | |
chain :and_call_custom_matcher do |custom_matcher| | |
@failure_message_custom_matcher = custom_matcher.failure_message | |
@matcher_block = custom_matcher.quick_matcher | |
end | |
failure_message do |actual| | |
@failure_message_expectation.to_s + @failure_message.to_s | |
end | |
end | |
Matcher = Struct.new(:quick_matcher, :failure_message) | |
quick_matcher = ->(first_expect, second_expect) do | |
first_expect.class == second_expect.class | |
end | |
matcher = Matcher.new(quick_matcher, "Class do not match") | |
it 'no fail' do | |
expect('u').to match_to_string('u').and_call_custom_matcher(matcher) | |
end | |
it 'with first failing matcher' do | |
expect('u').to match_to_string('v').and_call_custom_matcher(matcher) | |
end | |
it 'with second failing matcher' do | |
expect('u').to match_to_string(:u).and_call_custom_matcher(matcher) | |
end | |
it 'with both failing matchers' do | |
expect('u').to match_to_string(:r).and_call_custom_matcher(matcher) | |
end | |
end |
Author
benoittgt
commented
Jul 14, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment