Posted over 2 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, then you can simply 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

If you're only going to include a matcher once, you can also use the matcher macro within an example group for the same effect.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Andreas Robecke
Last edit:
6 months ago
by Henning Koch
Keywords:
local, localize
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 cookies to improve usability and analyze traffic.
Accept or learn more