The Joys of RSPEC in Rails

Elizabeth
2 min readJan 2, 2021

You may be familiar with RSPEC in Rails as a way to test your code. Today I am going to show you how to set up RSPEC yourself in Rails and thus write the tests to test your own code. Let’s start by adding gem "rspec" to your gem file under development, then (you guessed it) a bundle install. After you've done that run rails generate rspec:install in your terminal. This should create a spec folder with the following pages. You don’t need to touch these.

I also recommend visiting your .rpsec page, which will be at the top of your app, and adding --format documentation just so make your tests easier to read in the terminal. The following commands will create testing pages for your model and controller.

rails generate rspec:model MyModel
rails generate rspec:controller MyController

If you visit your model page you should see the following code already there:

require 'rails_helper' RSpec.describe Device, type: :model doend 

Inside RSpec:describe this is where you can write your methods. And this part is entirely up to you. For example on the code below I made some simple validation tests. Using the formula it ‘string’ do end you can write in anything. It tests to make sure my new instance of person has an attribute rating of nice higher than 5, for example. Here we have a new device has both a phone number and carrier attributes.

On your controller test, which is called request, conversely you can run the same of different tests with another it do end statement.

If your models are set up correctly, whatever you choose should run fine. Happy testing!

--

--