DEV Community

wshi9124
wshi9124

Posted on

Rspec- Ruby Testing Tool

“RSpec is a computer domain-specific language testing tool written in programming language Ruby to test Ruby code.

Why use Rspec:
Rspec is a great tool to use for test driven development(TDD). TDD is when you start by creating tests and then move to program the feature to pass the tests. TDD is used for documentation, handling edge cases, time efficiency and maintainability. TDD is considered the gold standard in the industry and is beneficial in the long run. However, writing good tests take time and might not be achievable due to deadlines and discipline.

How to install:
gem install rspec
How to check version:
rspec -v
Add testing to project:
rspec --init

First, make sure to have the gem 'rspec' inside the gem file and bundle install. Then initialize rspec with rspec --init in terminal.
Image description
For my example, I will be writing tests for a class Calculator. To do so, I will first create a calculator.rb file inside the lib folder and a calculator_spec.rb in the spec folder. I will also create an enviroment.rb in the config folder.
Image description
In the .rspec file, make sure to have --format documentation line inside. This will help you better view which tests are passing or failing when you run tests (rspec).
Image description
Image description
Since we have an enviroment.rb file, we should require_relative the calculator.rb file and require_relative the enviroment.rb file inside spec_helper.rb
Image description
Image description
After, we will make the class Calculator and describe Calculator inside the calculator_specs.rb file
Image description
Image description
Now that set up is done, lets write some basic tests
Structure of tests:
Image description
Image description
When we run rspec in the terminal, this is what we get back. it...do describes each individual test that we want to pass. context...do is optional, but useful to organize tests. expect is the core of how we make tests. For example, expect(subject.add(5,6)).to eq(11) means that the test is looking for an instance method called add that has two parameters and will return 11. We should write more than one expect in each method so that we can't "cheat" the tests.

Here are some other ways to write expectations:
I will also link documentation about expectations in the bottom of the blog
Image description
To pass these tests, lets go to our Calculator class and write some methods.
Image description
When we run rspec again, we can see that we passed all of our tests! Now you are ready to create your own tests in Ruby!
Image description

Rspec documentation and source:
https://rspec.info/documentation/
https://rspec.info/documentation/3.9/rspec-expectations/
Code and slides belong to Laura Berge:
https://github.com/lberge17/nyc-060622-rspec-intro
https://docs.google.com/presentation/d/132o4KFVVIZsPvPy8M9mROL3Nitd4PKBC0tN9QsKKvhg/edit#slide=id.g14510627d9b_0_130

Top comments (0)