Testing with RSpec .

Grace Mugoiri
3 min readAug 14, 2019

Testing is a mechanism almost no developer gets away with. And in this article I will talk about testing with RSpec on Rails which differ slightly with plain Ruby. I will be writing for plain Ruby in my next article so be sure to look out for that.

There are different tools used in testing but will focus on one. So what is RSpec? It is a Domain Specific Language testing tool specifically written in Ruby to test Ruby code. Its concept is more of TDD(Test Driven Development) where tests are prewritten before the code and later refactored according to the tests’ fulfillments.

sample test from my tic-tac-toe game.

How to start working on/with Rspec.

Go to Gemfile (assuming you have your app set up already, if not here is an article on how to set up your rails app) usually in the root directory (file color red) and add your rspec-rails to both the development and tests groups. It should look like this.

in your gemfile add rspec-rails

Then go to your terminal where your project is and run bundle install to download and install it on your project. Together with this run rails generate rspec :install to configure the files. Upgrade the bundle with bundle update rspec-rails if you have an older version in your project.

At the top of your files be sure to include your rspec with require 'rspec' .

Writing a test with Rspec

Go to your spec folder where you have test files for example in the user_spec.rb under models and describe the model in this case User like so:-

RSpec.describe User do  it "Is not validated when name is nil" do  user = User.new(name:"")  expect(user).not_to be_valid  endend

Run rspec from your terminal and just like this you have your first test. If you get error or failure come back to your test and check what is wrong as the error/failure will be described. If there is an error/failure it appears in color red and green if all was successful.

Here are a few descriptions of the terms(objects) used in the above code.

  • describe — used to describe the class or method in use(in this case the class User ).
  • it — used to describe the specifications of the sample in context(usually a string that says what is expected of the specific test).
  • expect — gives the state that something is expected to be done(eg be_valid, equal, respond_to, not_nil)

Why testing is important.

Test helps us in a few things namely:-

  • Useful in understanding changes in your system’s performance. If something breaks with help of tests it would be easier to identify.
  • Until you run or execute a line of code, you will not be certain if your code is actually working correctly.
  • Easily identify a bug.

--

--