Read more

Rspec: Scope your custom matchers to example groups

Andreas Robecke
June 05, 2016Software engineer

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

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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
Posted by Andreas Robecke to makandra dev (2016-06-05 19:52)