Posted over 5 years ago. Visible to the public. Repeats. Linked content.

Rspec: Scope your custom matchers to example groups

When you find yourself in the situation that you would like to define a custom matcher in your specs, but you do not want to define a global matcher since you need it only for your specific test, there are two ways to do it:

Custom matcher for a single group

If you're only going to include a matcher once, you can also use the matcher macro within an example group Archive :

Copy
describe "group" do matcher :be_just_like do |expected| match {|actual| actual == expected} end it "has access to the defined matcher" do 5.should be_just_like(5) end end

Custom matcher for some groups

If you are planning to re-use a matcher in multiple groups, put it in a module and include it only where you need it.

Since each describe block generates an anonymous class internally, this will include the matcher for this example group only.

Copy
require 'rspec/expectations' module MyHelpers extend RSpec::Matchers::DSL matcher :be_just_like do |expected| match {|actual| actual == expected} end end describe "group with MyHelpers" do include MyHelpers it "has access to the defined matcher" do 5.should be_just_like(5) end end describe "group without MyHelpers" do it "does not have access to the defined matcher" do expect do 5.should be_just_like(5) end.to raise_exception end end

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Andreas Robecke
Last edit:
over 1 year ago
by Henning Koch
Keywords:
local, localize, inline, limit
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Andreas Robecke to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more