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 Show archive.org snapshot :

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.

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
Andreas Robecke Almost 8 years ago