RSpec formatting and flags

Typically when you use the RSpec testing gem, everything is setup for you once you install the gem with the bundler. Today I want to look at how the files are typically structured, as well as how RSpec allows you to add flags into a specific file that makes looking at your tests output more productive.

For this example, let’s pretend that we are playing a card game and I want to run some tests on some of the cards that I have created.

First, let’s take a look at how the files are structured. Ruby files will be under the lib file path and your test files will be in the spec directory.

Tree Example

Now lets take a look at our card.rb file

Very basic card class

Let’s also peek at the test file.

card_spec.rb test file.

Note that you require ‘card’ — that’s the card.rb file (from the lib directory). This is important because RSpec needs to know what it is testing.

Also — I have not refactored some of the tests. This post is purely about how specs are structured as well as how to add flags for testing.

NEXT- Install rspec from the command line

Lets run our tests…

Ok so I have 5 tests that pass and none that fail. But what if I want more information? RSpec allows this. Simply create a .rspec file in the main directory and add any flags that you wish to have present.

.rspec file under main directory

Here are the contents of the .rspec file. It’s going to flag errors by color, it requires the spec_helper file and it will format the the tests to be a bit more readable. I’ll throw an error into the code so we can see how these flags work —

Test output with flags.

Now my tests give a bit more information thanks to the flags. I can see that the tests that pass are green and my failures are red. This is normal RSpec behavior, but the test methods are called as well, and that is helpful.

Here is the output without the flags and formatting.

Test output without the flags. You still see the green dots for passing tests, and the specifics for the failed test.

Hope you enjoyed how RSpec tests are structured in your Ruby code as well as how you can add flags to have a different visual output to your tests.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.