DEV Community

Cover image for Building Tests in Ruby: Expectations and Matchers
Tori Crawford
Tori Crawford

Posted on • Updated on

Building Tests in Ruby: Expectations and Matchers

In the first post of this blog series I discussed the basic components needed to build a test in Ruby. I briefly discussed the expect keyword and noted that we'd discuss it in further detail in a later post. Well, here we are!


When building tests in Ruby, expectations are a very important component. They allow you to set the intended results of the function, method, class, etc. that you are testing. The way that we set expectations in Ruby tests is by using expect("some code").to or, the opposite, expect("some code").not_to.

If you are thinking that these code snippets seem unfinished you are correct. There is one other component needed to finish an expect statement: matchers.


RSpec comes with built-in matchers that can be used alongside expect().to. When building tests, you'd expect the intended result to match the intention of the matcher. This may seem odd if you've never seen a matcher before but don't worry because they are pretty self explanatory. As I said in the first installment of this series, it is important to make your tests easy to read and RSpec gives us the tools to make this possible.

I am going to spend the remainder of this post discussing a few of the common matchers out there, but it should be noted that there are many more than what I am covering.


You would want to use the include matcher to test if a collection includes what is passed into expect().to. The test will pass if "any object of the given collection passes the specified matcher."

Code snippet of examples using include matcher


You can use start_with to test if a string or array starts with what is passed into expect().to.

Code snippet of examples using start_with matcher


Alternatively, there is also an end_with matcher. This matcher is used to test that a string or array ends with the code passed into expect().to.

Code snippet of examples using end_with matcher

Final Thoughts

We've gone over expect().to and matchers. I discussed three commonly used matchers. Please take a moment after this post and Google all the different matchers out there (there are a ton!).

Always keep in mind that when building RSpec tests you want them to be as reader friendly as possible. They should read like a sentence and RSpec gives us all of these amazing tools, like the expect keyword and matchers, to make it easy on us.

Happy coding!

Note: This weeks cover image is brought to you from a hike I took in Wunderlich County Park in Woodside, Ca.


Built in matcherst
Module: RSpec::Matchers

Top comments (0)