Matchers That Can Take Other Matchers

In RSpec, some matchers can take another matcher as an argument. It is sometimes useful for writing an expectation for a collection. Let's say we want to test that an array contains a string that includes a particular text. We can do that by combining two matchers: include and match as follows.

expect(an_array).to include(match(/Lorem/))
# Of course we also could do:
#   expect(an_array.grep(/Lorem/)).not_to be_empty
# or
#   expect(an_array).to be_any {|item| /Lorem/ === item }

I think that in this case, the expectation with include and match is much more concise than the commented-out alternative ways above.

Other matchers like all and have_attributes also accept matchers as arguments.

expect(an_array).to all(be_a(String))
expect(person).to have_attributes(name: match(/Lorem/))

See Also

Gentaro "hibariya" Terada

Otaka-no-mori, Chiba, Japan
Email me

Loves Ruby, Internet, and Programming.