Last active
November 11, 2023 06:09
-
-
Save r7kamura/19991db53e77d638ade11e4abce1e055 to your computer and use it in GitHub Desktop.
RSpec matcher with pattern-matching.
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
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'rspec' | |
end | |
require 'rspec/autorun' | |
RSpec::Matchers.matcher :match_pattern do |expected| | |
match do |actual| | |
eval(<<~RUBY, binding, __FILE__, __LINE__ + 1) | |
actual in #{expected.inspect} | |
RUBY | |
end | |
failure_message do |actual| | |
<<~TEXT | |
expected #{actual.inspect} to match pattern #{expected.inspect} | |
TEXT | |
end | |
end | |
RSpec.describe '#match_pattern' do | |
context 'when pattern-matching succeeds' do | |
it 'succeeds' do | |
expect([1, 2, 3]).to match_pattern([Integer, Integer, Integer]) | |
end | |
end | |
context 'when pattern-matching fails' do | |
it 'fails' do | |
expect([1, 2, 3]).to match_pattern([Integer, Integer, String]) | |
end | |
end | |
context 'when a pattern is passed that cannot be used as pattern-matching' do | |
it 'raises SyntaxError' do | |
expect([1, 2, 3]).to match_pattern(Object.new) | |
end | |
end | |
end |
Author
r7kamura
commented
Nov 11, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment