loading...

Anatomy of a Rspec Test

kahawaiikailana profile image Kailana Kahawaii ・2 min read

If you’ve used Ruby on Rails to build applications, you might have come across rspec testing. Rspec is a testing tool used to test Ruby programs. It follows Behavior Driven Development as it helps developers test out software.

Rspec uses several key words. The most important are:

Describe

  • Used at the top level of the test
  • Accepts a class name or string

It

  • A generic word that refers to a specific example

Expect

  • Used to define outcomes
  • Can be combined with to eq or not_to eq, to or not_to

Subject

  • An object being tested on

In order to practice writing rspec tests, we’re going going to create a rails project. This simple project will validate that a user enters their name to a form.

$ rails new test-names 

Add the rspec gem to the gem file.

gem 'rspec-rails'

In app, create a spec folder.

$ mkdir spec

In spec, create a models folder.

$ mkdir models

Within the models folder, create a user_spec file.

$ touch user_spec.rb 

The _spec at the end lets Ruby know this is a test file.

RSpec.describe User, type: :model do
[...]
end 

Here, we declare an rspec test for our User class.

subject {
   described_class.new(first_name: "John",
                       last_name: "Doe")
 }

Subject will stand in for an object (in this case, a user with a first and last name).

it "is valid with a first name" do
   expect(subject).to be_valid
 end

 it "is valid with a last name" do
   expect(subject).to be_valid
 end


Finally, we create a couple of test cases. The test uses the it keyword, followed by a description of the test. Then, the expect method is used to validate the subject being passed into it.

In order to run the test, go to the top level directory and run

bundle exec rspec

in the terminal.

Here is the entire test.

RSpec.describe User, type: :model do
 subject {
   described_class.new(first_name: "John",
                       last_name: "Doe")
 }

 it "is valid with a first name" do
   expect(subject).to be_valid
 end

 it "is valid with a last name" do
   expect(subject).to be_valid
 end

end

The test will run and display the number of examples, failures, and pending tests (if any).

Of course, the point of tests is to plan for user behaviors and behavior of the software. By building tests that are sure to fail at the onset, we can create more robust code and hopefully plan for user interactions.

Discussion

pic
Editor guide