Skip to content

Instantly share code, notes, and snippets.

@spencereldred
Last active January 2, 2016 21:29
Show Gist options
  • Save spencereldred/8363847 to your computer and use it in GitHub Desktop.
Save spencereldred/8363847 to your computer and use it in GitHub Desktop.
RSpec Testing of ruby programs

RSpec Testing

##BDD - Behavior Driven Development #Learing Objectives:

  • Understand BDD development flow

  • Install and configure RSpec

  • Understand basic RSpec blocks: describe, context, it

  • Understand how to write RSpec tests

  • Understand how to run RSpec tests

  • Understand how to make list of attributes and behaviors

  • Understand the Before and After blocks for test setup.

Behavior Driven Development Flow:

Mantra: Red, Green, Refactor

  • "Red" => write test, run test, test fails

  • "Green" => write just enough code to make it pass

  • "Refactor" => look for ways to improve your code

RSpec Testing Syntax Structure:

  • describe blocks

  • context block (optional)

  • it blocks

Sample code

describe "Object" do
  context "when created" do
    it "has an attribute X" do
      test code
    end
    it "has an attribute Y" do
      test code
    end
  end
end


describe "Object when created" do
  it "has an attribute X" do
    test code
  end
  
  it "has an attribute Y" do
    test code
  end
end	    

Installation

$ gem install rspec
$ rspec --v
$ rspec --help

Go to your working folder

$ rspec --init
	create spec/spec_helper.rb
	create .rspec

Edit .rspec ( use: "ls -a" to see the dot files)

.rspec:

--color
--format documentation

Move to the newly created "spec" directory

$ cd spec

Review spec_helper.rb

  • spec_helper.rb makes the RSpec tests are run in a random order.

Employee Code Along

Let's design an Employee class:

  • What attributes and behaviors should our Employee object have?

Create two files: employee.rb and employee_spec.rb

employee_spec.rb:

require 'employee'
require 'spec_helper'

describe Employee do

  employee = Employee.new("YourName")
  
  it "has a name " do
  	employee.name.should eq("YourName")
  	
  	# this syntax also works
  	# employee.name.should == "YourName"
  end
end

employee.rb

class Employee

	def initialize()
	
	end

end

Run RSpec Test

  • From the directory you ran $ rspec --init

  • Run $ rspec spec/employee_spec.rb

Special blocks: Before & After

  • Due to the random order of tests, you can't rely on the conditions of one test to setting up the other.

  • Eliminate the "order dependencies".

  • Before block runs before each test

  • After block runs after each test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment