52

What is the process for doing TDD in Ruby with RSpec without Rails?

Do I need a Gemfile? Does it only need rspec in it?

Ruby 1.9.3

B Seven
  • 44,484
  • 66
  • 240
  • 385
  • I'd assume it's pretty much the same as without, as there's no direct connection between rails and rspec. – Cubic Sep 06 '12 at 20:27
  • 2
    vimeo tutorial here: http://blog.codeship.com/install-rspec-tutorial/ – Rimian Jan 19 '15 at 01:05
  • It's a bit hard to see from the heading on the page and the title of the video, but this seems to be for both Rails and Rails-free Ruby projects. – B Seven Jan 19 '15 at 18:08

3 Answers3

76

The process is as follows:

Install the rspec gem from the console:

gem install rspec

Then create a folder (we'll name it root) with the following content:

root/my_model.rb

root/spec/my_model_spec.rb

#my_model.rb
class MyModel
  def the_truth
    true
  end
end

#spec/my_model_spec.rb

require_relative '../my_model'

describe MyModel do
  it "should be true" do
    MyModel.new.the_truth.should be_true
  end
end

Then in the console run

rspec spec/my_model_spec.rb

voila!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64
43

From within your projects directory...

gem install rspec
rspec --init

then write specs in the spec dir created and run them via

rspec 'path to spec' # or just rspec to run them all
Kyle
  • 21,978
  • 2
  • 60
  • 61
13

The workflows around gem install rspec are flawed. Always use Bundler and Gemfile to ensure consistency and avoid situations where a project works correctly on one computer but fails on another.

Create your Gemfile:

source 'https://rubygems.org/'

gem 'rspec'

Then execute:

gem install bundler
bundle install
bundle exec rspec --init

The above will create .rspec and spec/spec_helpers.rb for you.

Now create your example spec in spec/example_spec.rb:

describe 'ExampleSpec' do
  it 'is true' do
    expect(true).to be true
  end
end

And run the specs:

% bundle exec rspec
.

Finished in 0.00325 seconds (files took 0.09777 seconds to load)
1 example, 0 failures
Nowaker
  • 12,154
  • 4
  • 56
  • 62
  • This makes sense and is probably a best practice. However, it also makes the assumption that the purpose of using rspec here is automatically an open source and/or shared project. For the case where you just want to use rspec for local testing of say a user script, this may be overkill. – lacostenycoder Aug 31 '18 at 09:22
  • 2
    I'd hardly call those few lines "overkill", and would advise anyone to use bundler as shown in this excellent answer! – Timitry May 07 '19 at 13:50