arrow_backward Back to blog

RSpec the Unexpected

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.

arrow_backBack

New Project Request













Top