Classroom Lecture: Deep Dive into RSpec

In this live lecture I walk through various ways that you can utilize the RSpec testing library in pure Ruby and a production Rails app.

Video Lecture

In this live lecture I walk through various ways that you can utilize the RSpec testing library in pure Ruby and a production Rails app.

Code Transcript

Make sure to import the gem

require 'rubygems'
require 'rspec'

Basic Matcher

describe 'math' do
  it 'should 2 + 2 to equal 4' do
    expect(2 + 2).to eq(4)
  end
end

Testing a specific class

describe String do
  let(:string) { String.new }

  it 'should return a blank string' do
    string == ""
  end
end

Testing an Object with parameters

describe "user" do
  it "should have a full name" do
    User = Struct.new(:first, :last)
    user = User.new('Jordan', 'Hudgens')
    expect(user.first).to_not eq(nil)
    expect(user.last).to_not eq(nil)
  end
end

Creating a custom matcher

RSpec::Matchers.define :have_a_full_name do |user|
  match do |actual|
    user.first != nil
    user.last != nil
  end
  failure_message do |actual|
    "expected that #{actual} would have a first and last name"
  end
end

describe "user from custom matcher" do
  before do
    FromScratchUser = Struct.new(:first, :last)
    @user = FromScratchUser.new('Jordan')
  end

  it {should have_a_full_name(@user)}
end

To Run Tests:

rspec <file to test>

To Run Tests in Documentation Mode:

rspec <file to test> --format documentation

Jordan Hudgens

Jordan Hudgens

I've been a software engineer for the past decade and have traveled the world building applications and training individuals on a wide variety of topics.


View All Posts