RSpec Basics
Last updated
Last updated
The first thing we need when we start testing is a spec file for the tests we want to write. The convention dictates that we use the class name of the object we want to test, followed by the word _spec
. Then, of course, we need to give the file a suffix - in this case .rb
- our specs are written in ruby.
If we want to test a Car
class, our spec file will be named car_spec.rb
. Inside the spec file we will need to require
the file that we are running the test for.
For example we need to test car.rb
this means that we need to require car.rb
in our car_spec.rb
car.rb should be in the lib folder and car_spec.rb should be in the spec folder that was created when we ran the commandrspec --init
in the terminal.
Like everything we need to structure our test in order for them to make sense and for RSpec to understand what we want it to test. We will always have a describe block where we define our class or code. You can have several describe blocks inside another describe block in order for more structure in the file. You can view the describe block as a chapter for a book and the it blocks as separate pages in that book. You can also use the word the keyword context
when you want to use a describe
block inside another describe
block, the keyword context
is an alias for describe
and gives more clarity in some situations.
Expectations are our way to tell RSpec what we want it to test. The structure of an expect statement is
expect().to eq()
or expect().not_to eq()
There are four parts to an expectation expect
, expect-argument
, to
and the to-argument
( or not_to
argument).
Don't let the lack or precence of the brackets after the to fool you it is still an argument. Ruby gives us the option to skip the brackets if we want.
The image below shows a chart on the heirarchy on the structure of a spec suite.
This translates to