Set up a Ruby project with RSpec

Public, Testing / TDD, Ruby General


Created: Nov 12, 2017     Updated: Jan 30, 2019

1. First make sure you have rspec and byebug installed:

➜  byebug -v
  Running byebug 9.1.0
➜  rspec -v
RSpec 3.6
  - rspec-core 3.6.0
  - rspec-expectations 3.6.0
  - rspec-mocks 3.6.0
  - rspec-rails 3.6.1
  - rspec-support 3.6.0

If not, install them (gem install byebug or gem install rspec).

2. Next, create a directory for the project and initialize rspec in it:

➜  mkdir some-ruby-project
➜  cd some-ruby-project
➜  rspec --init
  create   .rspec
  create   spec/spec_helper.rb

3. Now create a class and associated spec, to test with:

➜  touch some_ruby_class.rb
➜  touch spec/some_ruby_class_spec.rb

4. Require the new class, and byebug gem, by adding this to the top of the spec_helper.rb file:

require_relative '../some_ruby_class' ## require every class
require 'byebug' ## require every testing gem

5. Write an initial spec in the new some_ruby_class_spec.rb file:

RSpec.describe SomeRubyClass do
  it "should test methods in SomeRubyClass.rb" do
    expect(SomeRubyClass.some_method).to eq "success"

6. Write an initial associated method to test In the some_ruby_class.rb file:

class SomeRubyClass
  def self.some_method

7. At the command line, from the root of the project, run rspec:

➜  rspec

Finished in 0.00245 seconds (files took 0.10619 seconds to load)
1 example, 0 failures

8. (optionally) Add a Gemfile

I'll add the Awesome Print gem to the Gemfile. From the root of the project run:

➜  touch Gemfile

In the Gemfile add:

source ''

gem 'awesome_print'

Bundle install the gem:

➜  bundle install

Require the gem in the spec_helper.rb:

require 'awesome_print'