How to use RSpec without Rails?

RubyRspecTddBdd

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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!

Solution 2 - Ruby

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

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB SevenView Question on Stackoverflow
Solution 1 - RubyErez RabihView Answer on Stackoverflow
Solution 2 - RubyKyleView Answer on Stackoverflow
Solution 3 - RubyNowakerView Answer on Stackoverflow