Matchi
Collection of expectation matchers for Ruby 🤹
Installation
Add this line to your application's Gemfile:
gem "matchi"
And then execute:
$ bundle
Or install it yourself as:
$ gem install matchi
Usage
Built-in matchers
Equivalence matcher:
eql = Matchi::Matcher::Eql.new("foo")
eql.matches? { "foo" } # => true
Identity matcher:
equal = Matchi::Matcher::Equal.new(:foo)
equal.matches? { :foo } # => true
Regular expressions matcher:
match = Matchi::Matcher::Match.new(/^foo$/)
match.matches? { "foo" } # => true
Expecting errors matcher:
raise_exception = Matchi::Matcher::RaiseException.new(NameError)
raise_exception.matches? { Boom } # => true
Truth matcher:
be_true = Matchi::Matcher::BeTrue.new
be_true.matches? { true } # => true
Untruth matcher:
be_false = Matchi::Matcher::BeFalse.new
be_false.matches? { false } # => true
Nil matcher:
be_nil = Matchi::Matcher::BeNil.new
be_nil.matches? { nil } # => true
Custom matchers
Custom matchers can easily be defined for expressing expectations. They can be any Ruby class that responds to matches?
, to_s
and to_h
instance methods.
A Be the answer matcher:
module Matchi
module Matcher
class BeTheAnswer < ::Matchi::Matcher::Base
def matches?
42.equal?(yield)
end
end
end
end
be_the_answer = Matchi::Matcher::BeTheAnswer.new
be_the_answer.matches? { 42 } # => true
A Be prime matcher:
require "prime"
module Matchi
module Matcher
class BePrime < ::Matchi::Matcher::Base
def matches?
Prime.prime?(yield)
end
end
end
end
be_prime = Matchi::Matcher::BePrime.new
be_prime.matches? { 42 } # => false
A Start with matcher:
module Matchi
module Matcher
class StartWith < ::Matchi::Matcher::Base
def initialize(expected)
super()
@expected = expected
end
def matches?
Regexp.new(/\A#{expected}/).match?(yield)
end
end
end
end
start_with = Matchi::Matcher::StartWith.new("foo")
start_with.matches? { "foobar" } # => true
Contact
- Home page: https://github.com/fixrb/matchi
- Bugs/issues: https://github.com/fixrb/matchi/issues
Versioning
Matchi follows Semantic Versioning 2.0.
License
The gem is available as open source under the terms of the MIT License.