Getting Started with RSpec — Part 1

Andy
6 min readAug 27, 2017

--

Note: This is the first post of the Getting Started with RSpec tutorial. This tutorial is designed for novice Ruby programmers wanting to learn how to add automatic testing to their apps.

TLDR: RSpec is a way of ensuring that your app does what you want it to do.

There are a few things that help good programmers become great programmers. Writing unit tests to ensure code stability is one of these attributes.

RSpec is an automated testing framework for Ruby. Testing frameworks are used by a developers to create tests for actions, functions, or methods in their program ensuring that the code runs properly. You can think of RSpec tests as any exam in a high school class. There is a baseline requirement (“C” Grade, for example) for someone to pass the class. RSpec tests ensure that your code passes the class with a C or better.

Testing is highly important and you can bet that any developer worth their salt knows how to write tests. The first step to using RSpec is to install it.

INSTALLING RSpec

RSpec can be installed via a Ruby Gem.

Gems are Ruby libraries developed by other programmers that quickly add functionality to a program. Gems are primarily used with Ruby on Rails applications, so if you get a little lost it’s okay. Just try to follow along.

To install a gem, we first need to make a Gemfile. A Gemfile is file that contains instructions on which gems to install. Inside of a Gemfile there are three pieces of information: a gem source, a list of gems, and their version numbers.

Let’s get started by creating a new folder called calculator and cd-ing into it inside of your terminal. Inside of this folder, make a new file namedGemfile (note the capital G and no extension) by running the command touch Gemfile . Open Gemfile with your text editor and add the following:

# calculator/Gemfile
source “https://rubygems.org"
gem ‘rspec’, ‘~> 3.6’

as you probably guessed, the source line tells the installer where to find the gem, and the gem line tells the installer which gem and version to install. The ~> symbol (formally called the “Approximately greater than” symbol) tells the installer to install any version greater than 3.6 but less than 4.0. Confusing, but let’s roll with it.

Now that we have our Gemfile set up, we will run the installer. From your terminal (still in the calculator directory), run the command bundle install

This will install the RSpec gem:

calculator $ bundle install
Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/.
Resolving dependencies…
Using bundler 1.15.3
Using diff-lcs 1.3
Using rspec-support 3.6.0
Using rspec-core 3.6.0
Using rspec-expectations 3.6.0
Using rspec-mocks 3.6.0
Fetching rspec 3.6.0
Installing rspec 3.6.0
Bundle complete! 1 Gemfile dependency, 7 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

BOOM! RSpec is now installed!

WRITING AN EXAMPLE PROGRAM

The easiest way to explain how RSpec and, later, Test Driven Development (TDD) works is by creating an example. Let’s write a calculator program that will add two numbers.

Create a file, calculator.rb by typing touch calculator.rb in your terminal window (still inside your calculator directory). Then, open the file in your text editor and write the program:

# calculator.rb
class Calculator
def add(x, y)
x + y
end
end

Then load it into irb to make sure it works:

calculator $ irb: 001 > load ‘./calculator.rb’
=> true
: 002 > calc = Calculator.new
=> #< Calculator:0x007f9ea882cb40>
:003 > calc.add(2, 3)
=> 5

Looks like it’s working! We expect the function add(2, 3) to equal 5 (and it does).

Now that we have a something to test, let’s write some tests to make sure it keeps working the way we want it to.

RSpec tests are named after the file they test. For our calculator.rb file, we will be creating a new file, calculator_spec.rb where all the tests will be written. All *_spec.rb files should be kept organized inside a spec folder. To make that folder, enter mkdir spec in your terminal, then create the calculator_spec.rb file by entering touch spec/calculator_spec.rb .

You’re all set to write your first RSpec test!

WRITING OUR FIRST TEST

Now that we’re all set up, it’s time to write the first test. Open the calculator_spec.rb file in your text editor and add the line:

require ‘./calculator.rb’

This line tells RSpec where to find the calculator program we wrote before.

At it’s core, RSpec describes how we want our program to behave. It’s syntax (a.k.a. Domain Specific Syntax) is meant to be fairly easy to read and figure out what’s going on. We’ll start off by describing the way we want the calculator to behave.

require ‘./calculator.rb’describe “calculator” do
it “adds numbers”
end

Just by reading this out loud you should be able tell what we will be testing. We will now run RSpec to make sure we have everything set up properly. From your terminal enter:

calculator $ rspec

and you should get an output similar to:


calculator $ rspec
*
Pending: (Failures listed here are expected and do not affect your suite’s status)1) calculator adds numbers
# Not yet implemented
# ./spec/calculator_spec.rb:4
Finished in 0.00172 seconds (files took 0.08711 seconds to load)
1 example, 0 failures, 1 pending

Everything is working. The test is pending since we have told RSpec that we will be testing the addition feature, but haven’t actually implemented the test yet. This is the last thing we will do.


require ‘./calculator.rb’
describe “calculator” do
it “adds numbers” do
calc = Calculator.new
expect(calc.add(2, 3)).to eql(5)
end
end

Similar to how we tested out the program in irb we expect the calculator add function to equal 5 when we add 2 and 3 together.

Now if we re-run RSpec we will see that the pending test has “turned green” and passed

calculator $ rspec
.
Finished in 0.00523 seconds (files took 0.08796 seconds to load)
1 example, 0 failures

TAADAA! You’ve just written your first RSpec test!

WHY IS TESTING IMPORTANT?

It’s common for many developers to be working on the same application. Writing tests ensures that the feature you’ve written performs as it should each and every time.

Take for example your coworker Matz, a developer who’s not so sharp. He is reading through your calculator code and he sees the add function and says to himself, “a.d.d. stands for Attention Deficit Disorder, not this weird x + y stuff”, so he refactors your code returning the string “ADD” instead of the sum of the two numbers.

# calculator.rb
class Calculator
def add(x, y)
“ADD”
end
end

But this isn’t what you intended your code to do, so when you run RSpec you get an error:


calculator $ rspec
F
Failures:
1) calculator adds numbers
Failure/Error: expect(calc.add(2, 3)).to eql(5)

expected: 5
got: “ADD”

(compared using eql?)
# ./spec/calculator_spec.rb:6:in `block (2 levels) in <top (required)>’
Finished in 0.01897 seconds (files took 0.09196 seconds to load)
1 example, 1 failure
Failed examples:rspec ./spec/calculator_spec.rb:4 # calculator adds numbers

Your RSpec test has caught the error. It expecting calc.add(2, 3) to equal 5, but getting the string “ADD” back instead

CONCLUSION

Although this first test may seem trivial, testing is an important component of any application. This tutorial is designed to show you the basics of testing with RSpec and getting you started. Large applications have thousands of tests to make sure each component is working correctly. As you write more and more tests you’ll realize the importance of them. Writing one good test can save you many hours in the long run by preventing you from hunting down a bug.

Please tune in later for the next installment of the Getting Started with RSpec tutorial where we will talk about Test Driven Development (TDD). If you have any questions please feel free to contact me by leaving a comment below.

--

--

Andy
Andy

Written by Andy

Web Developer, Marathon Runner, Coffee Drinker.

Responses (1)