Getting Started With CSpec-Rails
Yesterday I wrote a blog post about why Rails needs a better story for CoffeeScript development. Today, I'm going to describe a solution (not THE solution) for making it much nicer. We will be using CSpec and CSpec-Rails.
CSpec
CSpec is a RSpec-inspired library for CoffeeScript. The nice part about CSpec is that you are writing your tests in CoffeeScript for your CoffeeScript files. There is no need to compile either the specs or the code down to JavaScript.
CSpec runs on top of NodeJS. I realize that this is a large dependency for CSpec and is one of the things I would like to see if we can get removed. However, as of now, we're using NodeJS.
CSpec-Rails
CSpec-Rails is a simple gem that gives some Rails utilities for interating with CSpec. Currently, it only gives you a rake task that will run all of your Rails CoffeeScript specs for you. I have a few more things planned for this in the future but not much.
Getting Started
The first thing that you'll need is all the dependencies. I'm going to assume that you already have a Rails application so I will not be describing that. Next, we need to install NodeJS and NPM (Node Package Manager).
- Install NodeJS from http://nodejs.org
- Install NPM from http://npmjs.org
And now we've gotten our dependencies. To install CSpec, we just need to run npm install cspec.
Finally, just add gem 'cspec-rails' to your Gemfile, run bundle install and you are ready to start rocking some tests!
Simple Spec
In CSpec, we can assume that we have all of our coffeescripts compiled and ready to use. jQuery is also turned on by default. The following is a simple example of a spec:
describe "User", ->
spec ->
user = new User("Bob", "Saget")
user.firstName.should be "Bob"
spec ->
user = new User("Bob", "Saget")
user.lastName.should be "Saget"
spec ->
user = new User("Bob", "Saget")
user.getFullName().should be "Bob Saget"
We can run these specs by running rake cspec. It would then output:
Bob should equal Bob Saget should equal Saget Bob Saget should equal Bob Saget
This is all pretty preliminary and incomplete but it is a very encouraging start. There is a ton of work to do to make CSpec more usable and to get CSpec-Rails to do a little more heavy lifting for us.