Jan 15

New and Improved: RSpec 1.1.2

dastels @ 3:48 am

Tonight RSpec-1.1.2 was released. See most of the details on David Chelimsky’s blog.

I take a personal interest in this release as it includes my first active submission to the codebase in some time.

The functionality I added relates to the definition of steps in the new story component. Up until now, you used a string to define a step. For example:

Given "a student named '$name'" do |name|
  #...
end

When "the student is given a grade of $grade" do |grade|
  #...
end

Then "the student should $pass_fail" do |pass_fail|
  #...
end

This would result in stories like the following:

Given a student named 'Mike'
When the student is given a grade of 40
Then the student should fail

Continually talking about “the student” is grating and very un-natural sounding. Sounds downright, bloody legalistic, actually. And a lawyer is the last thing we want to be accused of sounding like… other than maybe Denny Crane.

One approach to this would be to go to something like:

When "he is given a grade of $grade" do |grade|
  #...
end

Then "he should $pass_fail" do |pass_fail|
  #...
end

which would give us:

Given a student named "Mike"
When he is given a grade of 40
Then he should fail

Now, speaking of lawyers, we probably want to make this a little more PC and be able to do this:

Given a student named "Michelle"
When she is given a grade of 60
Then she should pass

We could conceivable create another set of steps for the feminine forms, refactoring to remove the duplication. That might suffice in the simple case, but it’s still rather crude. I’d like to be able to use a regular expression and create steps something like:

When /(he|she) is given a grade of (.*?)/ do |pronoun, grade|
  #...
end

Then /(he|she) should (.*?)/ do |pronoun, pass_fail|
  #...
end

With release 1.1.2, that’s exactly what you can do.

There are a couple things to point out:

  1. Alternatives need to be in a group to limit their scope.
  2. Whatever matches groups such as that (and any others) will be sent into the supplied block as arguments. As such they need to be accommodated by having a block parameter for each of them.
  3. Since this is already a regexp, no internal processing is done to it. With string step names, variables (of the form $<identifier>) are rewritten as (.*?). When using a regexp as the step name where there are variables, we much do this rewriting ourselves.

This new feature provides a new level of flexibility in defining story steps. Have fun with it.

Tags: 

Leave a Reply