
In the firstpost of this blog series I discussed the basic components needed to build a test in Ruby. I briefly discussed theexpect
keyword and noted that we'd discuss it in further detail in a later post. Well, here we are!
Expectations
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 setexpectations
in Ruby tests is by usingexpect("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 anexpect
statement:matchers
.
Matchers
RSpec comes with built-inmatchers
that can be used alongsideexpect().to
. When building tests, you'dexpect the intended result tomatch the intention of thematcher
. This may seem odd if you've never seen amatcher
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 commonmatchers
out there, but it should be noted that there are many more than what I am covering.
include
You would want to use theinclude
matcher to test if a collectionincludes what is passed intoexpect().to
. The test will pass if "any object of the given collection passes the specified matcher."
start_with
You can usestart_with
to test if a string or arraystarts with what is passed intoexpect().to
.
end_with
Alternatively, there is also anend_with
matcher. This matcher is used to test that a string or arrayends with the code passed intoexpect().to
.
Final Thoughts
We've gone overexpect().to
andmatchers
. I discussed three commonly usedmatchers
. Please take a moment after this post and Google all the differentmatchers
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 theexpect
keyword andmatchers
, 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.
Sources
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse