Bootstrapping RSpec Generation
Written by steve on 04-17-2007 at 09:17 PM
For existing projects, I find myself spec’ing ex-post-facto (which I know is not the true spirit of BDD :). I go through iterations like:
- read the code and find all the methods
- put them in a new spec file
- try to say something interesting about their expected behavior
- get the specs to pass
- run rcov
- go back to 3
I decided to write a tool to do very crude parsing of Ruby files to yank out public methods to be spec’ed (my own presumption being that behavior can be spec’ed by describing the public methods). Because it is so Rails-biased, It also makes the assumption that the code to be spec’ed is expressed as class methods rather than at the module level.
The tool is here.
Usage is:
ruby spec_todo.rb <files>
So, for example, I might use it as follows:
ruby spec_todo.rb app/models/* app/controllers/*
Here is a brief example of the output of this tool:
#------------------------------------------------------------
# File: app/controllers/contact_controller_spec.rb
#------------------------------------------------------------
require File.dirname(__FILE__) + '/../spec_helper'
describe "A ContactController" do
controller_name :contact
integrate_views # comment out if you spec views separately
it "should do something sensible with index." do
# Your spec here
end
it "should do something sensible with thank_you." do
# Your spec here
end
end
This is somewhat fashioned after ZenTest’s ability to generate test scaffolding, but makes no attempt to integrate the scaffolding with existing specs, preferring to echo results to stdout.
At present, this “spec-todo” tool does not create any specs for validations. It completely ignores mix-in and inherited methods. Why? Well, try this exercise:
>> Cart.public_methods(false).length
=> 254
>> Cart.public_methods(true).length
=> 389
As you can see, even excluding methods that are not considered “in the receiver,” I have 254 methods in my Cart model. So, using Ruby’s introspection to yank methods out seemed like more of a noise generator than a time saver.
See if you like it.
0 comments