Back to Blog

Get in Touch

RSpec the Unexpected

By Joe Grossberg March 25, 2010 in testing rspec

Missing

Recently I came across the need to refactor a web service. I knew I wanted to build a safety net of unit tests first — ones verifying that, given a specific HTTP request, I would get a specific JSON response. The snag: this application is written in PHP and my favorite testing framework is RSpec

Would I be able to use RSpec, I wondered, on a project that wasn't Rails, Merb or even Ruby at all?

I am happy to report that, yes: despite its embrace of the convention-over-configuration philosophy, RSpec is flexible enough to use for non-Ruby projects.

It is quick and easy to get some tests up-and-running completely outside the context of a Ruby-based web framework.

In fact, you only need two files to make it happen, as you can see in the proof-of-concept screenshot below:

terminal output, demonstrating RSpec

I've made these files available in a github repository, but I will walk you through them below.

The Rakefile is just four lines that include the spec task via a require statement and set the configuration options inline:

require 'spec/rake/spectask'
Spec::Rake::SpecTask.new do |t|
  t.spec_opts = ['--colour', '--format=specdoc']
end

And the tests themselves? You just need to put them in one or more folders under spec/ and follow the naming convention of something_spec.rb. (You can override this, if desired.) In this case, I used very simple tests for demonstration purposes.

Then, all it takes is rake spec and, Voilà!, and you can run RSpec tests for a project that isn't based in Ruby!

Note: This was tested with ruby 1.8.7 and rspec 1.3.0; different versions may require some tweaking.

Medium

Joe Grossberg

Joe brings over a decade of professional front- and back-end web development experience to the table, with expertise in Ruby on Rails and JavaScript. He also organizes monthly meetings for the DC Ruby Users Group. Prior to working at Intridea, Joe was a software engineer at Revolution Health, where he developed enterprise-level B2B and D2C applications.

More posts by Joe Grossberg

Joe Grossberg

Finding it hard to get a local group started, or to keep one going? DCRUG has...

Joe Grossberg

Think RSpec is only for testing ruby? Think again! It is simple and quick to ...

Joe Grossberg