Testing with Rspec

Created by Sorcha Abel, @sabel25

Rspec is a testing framework. Simply put you write code to test other code. Rspec tests that a portion of code outputs the desired behaviour in a controlled environment. Given..when and then is the basic structure of all tests

COACH: Talk about given..when..then ie. Given some context..when an particular event occurs…then the result should be. Rspec is written in Ruby using a DSL

Install Rspec

To add rspec to your rails application open the file Gemfile in the root of your project, add the following lines and save

group :development, :test do
  gem 'rspec-rails'
end

Then we type the following command in the terminal while in our project directory. We do this to install the gem we just added

bundle install
rails generate rspec:install

This will create two files, rails-helper.rb and spec_helper.rb in the spec directory for you. All tests will be stored in this directory inside your project.

Next we will create a spec to test the idea.rb model we created earlier with out scaffold. But before we do that we need to modify the model idea.rb

Open this file in the app/models folder and add this line. The change we are making simply means that each idea we add via our browser page must have a name. Otherwise it is not considered to be a valid record and will not save to the database.

validates :name, presence: true

Next step is inside the spec directory where we create 2 new directories and one file (spec/app/models/idea_spec.rb)

  1. The first directory is called app. Once created double click to open it.
  2. The second directory is called models. Once created double click to open it.
  3. Inside the model directory create a file called idea_spec.rb

COACH: talk about the format of a rspec file i.e. filename_spec.rb

require 'rails_helper'

describe Idea do
  it 'will not save without a name' do
    idea = Idea.new
    expect(idea).to_not be_valid
  end
end

Finally go back to your terminal window and run

bundle exec rspec spec/app/models/idea_spec.rb

What’s next

practise practise practise.

Additional Guides