[rspec-users] BDD / cucumber thought - chaining 'Then' steps with Which

David Chelimsky dchelimsky at gmail.com
Fri Sep 26 08:33:02 EDT 2008

On Fri, Sep 26, 2008 at 6:30 AM, Matt Wynne <matt at mattwynne.net> wrote:
> Going back to the debate about keeping state between steps, I found myself
> with the mild urge to be able to write this today:
> Given there is a user
> And the user has 20 friends
> Then I should see a thumbnail of each of the users's friends
> Which should be a link to the user profile page for that friend
> NB: An idiom in this which may be songkick-only but was inspired by what
> we've read on this list, and worth explaining: "the user" as in "the user
> has 20 friends", means User.first in rails. If there's more than one user
> when this step runs, it will flunk, because the English no longer works.
> So anyway, what I was thinking was that it would be nice to be able to refer
> to the last thing I said I should be able to see, and decorate it with more
> specification in a subsequent step or steps.
> Obviously, I could roll these into one long Then step, but maybe this is
> more elegant...
> Just thinking out loud. I have no idea what the steps code would look like.

One of the promises of using treetop is the ability to extend the
grammar yourself to include keywords like Which.

As for maintaining state across steps, I know that Aslak recommends
avoiding this on the cucumber wiki, but I can tell you I've not once
(as in never ever ever) been bitten by doing this. I've got a couple
of helper methods I use to create and retrieve instance variables that
are uniquely named. See http://gist.github.com/13087.

Including that module in env.rb allows me to do this:

Given a user with login "ernie" and password "rubber"
And a user with login "bert" and password "duckie"
And ernie is assigned the admin role
And bert is assigned the contributor role

Given /^a user with login "(.*)" and password "(.*)"$/ do |login, password|
  create_user_named(login, password) do |user|
    set_ivar :user, login, user

Given /^(.*) is assigned the (.*) role$/ do |login, role|
  get_ivar :user, login do |user|

... thus creating and retrieving instance variables named user_ernie
and user_bert with different roles.

Other people have experiences, positive or negative, sharing state
across steps with instance variables?

> cheers,
> Matt
> ----
> http://blog.mattwynne.net
> http://songkick.com
> In case you wondered: The opinions expressed in this email are my own and do
> not necessarily reflect the views of any former, current or future employers
> of mine.

More information about the rspec-users mailing list