Test Driven Development in Ruby on Rails using Rspec

Test Driven Development (aka TDD) is where you create test specs of expected outcomes. You can then code your way to pass these tests. The opposite of this method of coding is Behavioral Driven Development (BDD).

Setting up

First thing we need to do is install the ‘rspec-rails’ gem. We want this in the development test section in our gem file.

Don’t forget to bundle install!

We can then create our rspec files using

rails g rspec:install

For this example let’s pretend we have 3 models. User, Cart, and Item.

When we use:

rails g resource Model attribute:type

The rspec file will be created for that model. To manually generate the file we can use

rails g rspec:model model_name

Creating a test

Lets create a test that totals all items in a users cart. Inside the user_spec.rb

Inside the #setup we are creating test cases. Inside the #verify we have:

expect(user.total_cart).to eq(5.00)

Coding to the Test Specs

When we run rspec we get the following error:

We can see NoMethodError for total_cart. So lets create a method for that in the User model.

We got rid of no method error, but we expected 5.0

So let’s see if can code something to pass this test spec.

After coding out the method and running rspec, we can see we passed the test!

Why TDD?

In the above example, we used a very easy test scenario. But what if it was more complex? What if we wanted to refactor? We can always test our code against the expected outcome. We can also zero in to where our code breaks.

For more documentation on Rspec-rails check out the docs here.

Fullstack Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store