Posted about 3 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.

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) 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Andreas Robecke
Last edit:
12 months ago
by Henning Koch
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