Repository navigation
Custom matcher example
Cyril Kato edited this page Nov 1, 2026
·
1 revision
A matcher is any object with match?, which takes the block giving the actual value and answers true or false, and to_s, which describes it. to and not_to take it as it is, and a let gives it a word.
require "r_spec"
class BeOdd
def match?
yield.odd?
end
def to_s
"be odd"
end
end
RSpec.describe Integer do
let(:be_odd) { BeOdd.new }
it { expect(3).to be_odd }
it { expect(4).not_to be_odd }
end$ ruby spec/custom_spec.rb
spec/custom_spec.rb:16: Success: expected 3 to be odd
spec/custom_spec.rb:17: Success: expected 4 not to be oddA specification of Fix is a matcher too, through matchi-fix:
require "r_spec"
require "fix"
require "matchi/fix"
Fix :Duck do
on(:quack) { it MUST eq "Quack!" }
end
class Duck
def quack = "Quack!"
end
RSpec.describe Duck do
let(:fix) { |name| Matchi::Fix.new(name) }
it { expect(Duck.new).to fix(:Duck) }
it { expect(Object.new).not_to fix(:Duck) }
end