Hermetic Testing with Rspec - Part 2

Your First Test


Let's suppose we have some pencils. Pencils can be of different colors, and we can set Pencils to be any color we want.

We will first create Pencils as its own PORO — plain old Ruby object.

Let's begin by writing a spec.


Run the rspec generator to create a pencil spec


rails generate rspec:model pencil



require 'rails_helper'

RSpec.describe Pencil, type: :model do

 it "should create a pencil" do

  expect(Pencil.new).to be_a(Pencil)

 end

end


Then run your spec and watch it fail. You are now RED on the RED-GREEN-REFACTOR cycle.


Remember, always use the testing process to describe the code you want. In this fashion you will consistently describe the code you want first, then implement only as much code as to make your test pass.


To implement this spec, all we have to do is create a Pencil class at app/models/pencil.rb


class Pencil

end



Let's go one step further and give our pencil a color attribute.




require 'rails_helper'


RSpec.describe Pencil, type: :model do

 subject {Pencil.new}


 it "should create a pencil" do

  expect(subject).to be_a(Pencil)

 end


 it "should have a color attribute that will default to nil" do

  expect(subject.color).to be(nil)

 end


 describe "#set_color" do

  before(:each) do

   subject.set_color("red")

  end


  it "should have a color attribute that can be set" do

   expect(subject.color).to eq("red")

  end

 end


And our implementation code:

class Pencil

 attr_accessor :color


 def set_color(color)

  @color = color

 end

end


We are now GREEN in the RED-GREEN-REFACTOR cycle. This means that we can proceed to add new features by adding specs first, then implementing those features. We can also refactor the existing features with confidence knowing that there are automated specs covering expected results.

This is why it is called "RED-GREEN-REFACTOR" cycle. By continuously providing feedback to us the developer, the test cycle allows us to work exponentially smarter, which in turn gives us incredible powers to produce code that is open to being refactored and resilient to change.