RSpec in your Ruby on Rails app
Test Driven Development (TDD) is the workflow improvement process where before writing any code, specific tests are written based on individual requirements of the final project. Once the tests are in place, developers write code in small chunks with the goal of passing the tests and thereby completing the requirements of the final product. If you are curious why it is useful, I recommend this blog by Godswill Okara.
This blog is going to detail the steps you need to take to get your first RSpec tests written and running so that you can begin to add to your Rails app using TDD!
First, add the rspec-rails app to your gemfile in both the “development” and “test” groups, as seen below.
group :development do
gem 'rspec-rails', '~>3.5'
endgroup :test do
gem 'rspec-rails', '~>3.5'
end
Run:
bundle install
We need a ‘spec’ folder for our test files, which can be made manually or with the command:
mkdir spec/
To add a few necessary configuration files, run the command:
rails generate rspec:install
You this adds three new files:
.rspec
spec/spec_helper.rb
spec/rails_helper.rb
Now you are ready to write tests! Let’s write our first tests for the Student model of an instructor review app. Add a “models” folder to spec, and in it create a file:
student_spec.rb
This is where you will write your tests!
Our first test will ensure that when a new Student instance is created, they have a username. Make sure you require ‘rails_helper’ at the top!
Here we have used the RSpec test to create not one but two students, and are testing that the second student created was accurately assigned his username and saved.
Let’s add a second test! One requirement that we want in our program is to have validations upon creation of new users. For example, a student should not be allowed to be created without a first name. We are going to write a test that will pass when that validation is written. Take a look at our new test:
The test above tries to create a student, but fails to put in a first_name attribute. If we properly write a validation on the student model that requires the presence of first_name, this test should pass.
Now that we have our tests, we can run in the terminal:
rspec
Because we wrote the code to pass the tests, we get the satisfying response of 2 examples, 0 failures. We can continue to write more tests and code that makes them pass! Good luck!