September 19, 2013

How to test Ruby scripts with RSpec?

Do you know how to test standalone Ruby scripts? With RSpec?

Well it is pretty easy when you know how to do it. But it took me some time to figure it out. So here you can find simple how to.

1) Add RSpec to your Gemfile

source ''
ruby '2.0.0'

gem 'rspec'

2) Create spec directory and spec_helper.rb file, which can be empty for now.

mkdir spec
touch spec/spec_helper.rb

3) Write some test

# spec/your_class_spec.rb
require 'spec_helper'
require 'your_class'


4) Create your class in lib directory. This is important! It has to be in lib directory, otherwise RSpec will not find it.

# lib/your_class.rb
class YourClass

5) Test it with rspec command and follow TDD! ;)

And you are done!

As I said, it is pretty easy, right? But it took me some time to find out where to put which files...

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.