RSpec, Testing in Ruby

Why should we test?

Daniel Glover
4 min readJul 8, 2019

Writing tests for your application can give us, the developer, a safety net against errors. It helps to document your code — keeping track of it — and monitor your code for smell! With TDD, we are getting feedback telling us where we should focus next, like a detailed instruction manual. Most importantly, we are making sure our code does exactly what we want it to, not just what we expect it to.

What is RSpec?

The Ruby programming language has a unit test framework, called RSpec. RSpec is a Behavior Driven Development tool, this means that its tests are written to focus on the “behavior” of an application rather than the emphasis of how it works. How does it behave, what does the application do?

RSpec files are known as as ‘specs’, we can think of this ‘spec’ file as our test file. Spec is short for specification.

How to use RSpec

Since RSpec is a BDD (behavior driven development) testing tool, it focuses on what the application does and if the application follows the specifications. The specification is best explained in terms of a user story. RSpec is designed with clarity in mind, pointing out whether the targeted code is running as expected.

Step 1.) We’d need to install the RSpec gem.

// gem install rspec

Step 2.) We will need to create a describe block. It will tell RSpec what we’re testing.

Step 3.) Now, we have the it block. This is the test’s name we’ve decided upon.

Step 5.) We’ll introduce the behavior we’re expecting from the targeted code…

Step 4.) Now we’d want to write out a method inside the multiplication class to implement the logic we’re testing for, so as to pass the test. If we were to run this test, we’d get…

We can fix this by creating the sum_of method inside the Multiplication class.

Then, upon running this code we’d get the next error with a detailed explanation as to who to resolve this issue.

This is a great place to be, as the feedback we’re getting from running the test is giving us a good idea of how to resolve the error. We need to provide two arguments to this method. I’m going to add two required arguments for the sum_of method.

And running this, will leave us with this new instruction…

Step 5.) (But technically 7 or something I’ve lost count) We need to write out the logic inside the sum_of method to get this test passing. The test is expecting 10 * 10 to equal 100. To get the test passing all we need to do is implement that simple logic to our sum_of method and we should be good.

Here’s the code…

And here’s a screen shot of the test passing;

That’s it for now, stick around for part 2

--

--