Story Driven Development with Rails - Part I: Up and Running

September 16, 2008

Earlier this year at the Gotham Ruby Conference, Brian Helmkamp gave a talk on Story Driven Development. It's a fantastic talk, I suggest that everyone view it. In it he explains how to use RSpec Users Stories combined with Webrat for full-stack executable scenario testing. He also covers what value executable scenarios provide and where executable scenarios fit into your overall web application testing strategy. This article provides you with a more detailed how-to of the steps required to get up and running with Story Driven Development with Rails.

In this article I don't go to much into the details of how story runner works, so I would say another prerequisite for this article is Geoffrey Grosenbach's RSpec User Stories available on PeepCode.

So let's say we are building a rails version of this blog. First steps are the basic rails setup:

$ rails blog
$ cd blog
$ script/plugin install git://github.com/dchelimsky/rspec.git -r 1.1.4
$ script/plugin install git://github.com/dchelimsky/rspec-rails.git -r 1.1.4
$ script/generate rspec      
$ script/plugin install git://github.com/ratnikov/fixture_replacement2.git 

That gives us an rspecified Rails app, which has a stories directory, all ready for us to put our stories in. Fixture Replacement is an implementation of the factory pattern for creating test data, which is an alternative to using fixtures data in yaml files. So let's create the first story in stories/view_articles_story.txt:

Story: View Articles

As a reader of the blog
I want to view articles
So that I can read what you have to say

  Scenario: display most recently published articles

    Given 5 articles have been published
    When I visit the homepage
    Then I should see the articles

A couple of things to point out. First, the naming convention I'm going with is to put the plain text story in <story_name>_story.txt and the story runner file in <story_name>_story.rb. Next I'd like to talk a little bit about this story. I choose to write this story first because it is the most important feature in the application. Generally I like to try to follow this rule. When writing a stories, always write a story for the next most important feature.

So in order to use this story, we need a runner. So let's put this into stories/view_articles_story.rb:

require File.dirname(__FILE__) + "/helper"

run_story :view_articles

This is about concise as it gets for this file. The magic happens in stories/helper.rb. Add this to the bottom of that file:

def run_story(story_name, options={})
  with_steps_for(story_name) do
    run(
      File.join(File.dirname(__FILE__), "#{story_name}_story.txt"), 
      { :type => RailsStory }.merge(options)
    )
  end
end

What this does is allow you to call run_story to run a story. It assumes by default that you will want to use the steps that are defined in the same file with the same name as the story. We'll probably enhance run_story in the future to do more stuff, but this is all we need for now. Now you can run either stories/all.rb or stories/view_articles_story.rb and you should get:

Running 1 scenarios

Story: View Articles

  As a reader of the blog
  I want to view articles
  So that I can read what you have to say

  Scenario: Homepage

    Given 5 articles have been published (PENDING)

    When I visit the homepage (PENDING)

    Then I should see the articles (PENDING)

1 scenarios: 0 succeeded, 0 failed, 1 pending

Pending Steps:
1) View Articles (Homepage): 5 articles have been published
2) View Articles (Homepage): I visit the homepage
3) View Articles (Homepage): I should see all 5 articles

So we now have yellow (a.k.a pending) scenarios, so step 1 is done. The next step is to write step matchers, which should make our scenario fail. So we add this to stories/view_articles_story.rb:

steps_for(:view_articles) do
  Given "$count articles have been published" do |count|
    @count = count.to_i
    @count.times {|n| create_article(:title => "Article ##{n}") }
  end
  When "I visit $path" do |path|
    get path
  end
  Then "I should see the articles" do
    @count.times do |n|
      response.should have_tag("h2", "Article ##{n}")
    end
  end
end

Make sure to add that before the run_story :view_articles line. Now you should have red (a.k.a failing) scenarios, that look something like this:

FAILURES:
    1) View Articles (Homepage) FAILED
    NoMethodError: undefined method `create_article' for   
    #<ActionController::Integration::Session:0x208bfe0>

Make sure they are failing for the right reason. For example, when I first wrote this, I forgot that all the of variables are captured as strings and I left off the call to .to_i on count. I get failing specs, but not because I haven't implemented the code, because my steps are wrong. Remember, tests can have bugs too.

Let's take a look at each of these steps. Inside the given step, we are calling create_article. Now as you noticed from the failure message, there is no create_article method yet. Fixture Replacement will take care of defining that for us once we have the articles model created and example_data.rb created. In the when step, we are capturing the path the user is trying to access, and then using the same rspec controller helper method we would use if this were a controller spec. get /some_path goes through the routing to call our controller with an HTTP get. Finally, in the then step, we just check that the HTML in our response has an H2 element with the title of the article in it, for each of the articles we created in the given step.

So now on to step 3, which is to write the code to make it go green. To make this easy, we'll use the rspec scaffold generator:

$ script/generate rspec_scaffold Article title:string body:text
$ rake db:migrate
$ rake db:test:prepare

So if we run stories/view_articles_story.rb again, we get the same error. That's because we still haven't told Fixture Replacement about our article model. So create the file db/example_data.rb and put this in it:

module FixtureReplacement
  attributes_for :article do |a|
    a.title = "First Post!"
    a.body = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit..."
  end
end

This defines the minimum set of data required to create a valid article. You can override any value by simply passing it in the hash, as we are doing in the given step. Fixture Replacement gives you two methods for each model, which are in this case, create_article and new_article, which do pretty much what you would expect. You can read more about Fixture Replacements in the README.

Last but not least, we have to include FixtureReplacement in our RSpec Story Runner, which is as simple as adding the line include FixtureReplacement somewhere near the top of stories/helper.rb, after all the other require statements.

So now if we run our story, we get something like:

1) View Articles (Homepage) FAILED
    Spec::Expectations::ExpectationNotMetError: 
    Expected at least 1 element matching "h2", found 0.
    <false> is not true.

Which is still failing, but it's progress. Obviously the problem now is that our view isn't outputting H2 elements for the article titles. That's an easy fix which I'll leave as an exercise to the reader (hint: modify the default route, edit the articles index ERB template).

One might argue that checking for H2s is checking the implementation details, which could be fragile if our designer decides to use DIVs instead, for example. That decision is up to you, personally I like to produce the correct semantic markup, have my tests validate that and apply CSS from there. If you'd rather your tests be less coupled to the DOM structure, you could just change your expectation in the then step to response.should have_text("Article ##{n}").

Hopefully that gets you up and running with Fixture Replacement and RSpec User Stories. Tune in for Part II of the series, where we cover more complex interactions with Webrat.

Posted in Technology | Tags RSpec, Rails, FixtureReplacement, Ruby, StoryRunner

Comments Comments Feed

1. Will give this a thorough reading later, thanks for taking the time to put this together.

Joc

# Posted By Joc on Wednesday, September 17 2008 at 5:54 AM

2. A very interesting write-up. Thanks.

Have you looked into replacing RSpec's User stories with Cucumber ?

Hamza

# Posted By Hamza on Sunday, December 21 2008 at 1:29 PM

3. Excellent article and nice information to share with users, http://www.cyberdesignz.com/ ,
you can get more feedback from this.

# Posted By jhon on Monday, January 5 2009 at 7:51 AM

4. Story Driven Development (SDD) helps close the gap between the language of developers and product owners so they can clearly define when software is “done”. Readable and executable product requirements are now possible. We’ll explore tips for integrating SDD into your existing workflow and cover technical details for implementing and maintaining stories using cutting-edge tools and libraries.Thanks for the update.Great post

# Posted By Poker Math on Thursday, July 23 2009 at 2:21 AM

5. Rails version of the code is so easy to apply as far as I know!!

# Posted By Freelance web designer on Saturday, August 21 2010 at 6:38 PM

6. This post is exactly what I am interested.

# Posted By Lasix on Tuesday, August 24 2010 at 12:31 PM

7. I really like your ideas!
Great information in here, Thanks for sharing it.

# Posted By robseller81 on Thursday, August 26 2010 at 7:06 AM

8. The resource like the one you mentioned here will be very useful to me! I will post a link to this page on my blog.

# Posted By chase personal loans on Friday, August 27 2010 at 3:39 AM

9. how to get up and running with Story Driven Development with Rails.this article explane about this topic seriously.

# Posted By phentermine 37.5 on Friday, August 27 2010 at 8:10 AM

10. I like Fixture Replacement

# Posted By Phoenix Pools on Saturday, August 28 2010 at 12:48 AM

11. I will let you know if its work for me too.Its always good to learn tips like you share for blog posting.As I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me.

# Posted By Johnlawyer299 on Saturday, August 28 2010 at 1:17 AM

12. I will let you know if its work for me too.Its always good to learn tips like you share for blog posting.As I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me.

# Posted By Atlanta divorce attorney on Saturday, August 28 2010 at 1:18 AM

13. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 3:08 AM

14. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 3:08 AM

15. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 3:09 AM

16. I completely agree with you. I really like this article. It contains a lot of useful information. I can set up my new idea from this post. Thanks so much!

# Posted By carpet cleaner Monterey on Saturday, August 28 2010 at 3:50 AM

17. one you mentioned here will be very useful to me! I will post a link to this page on my blog.

# Posted By Hollywood Couples on Saturday, August 28 2010 at 9:36 AM

18. Cialis e usato per il trattamento della disfunzione erettile negli uomini. E 'l'unica droga che non e solo ad azione Acquisto Viagra rapida (opere in 30 minuti), ma e anche efficace, a patto che 36 ore, che consente di scegliere il momento giusto per voi e il vostro partner. Milioni di uomini sono stati convinti di Cialis efficacemente in lieve, moderata o grave ED.

# Posted By Zyban on Saturday, August 28 2010 at 4:58 PM

19. Applications have no way of knowing they have to put aside the pages in the middle, for any of these functions, in theory, require all applications to be re-encoded for use and can be in dialogue form individual, which is not ideal. Thanks for sharing. Sincerely,

# Posted By video games on Saturday, August 28 2010 at 7:27 PM

20. thanks for the post. I agree with the information

# Posted By satellite tv for pc on Sunday, August 29 2010 at 6:28 PM

21. The beauty of these blogging engines and CMS platforms is the lack of limitations and ease of manipulation that allows developers to implement rich content and 'skin' the site in such a way that with very little effort one would never notice what it is making the site tick all without limiting content and effectiveness.

# Posted By Used Stationary Bikes on Monday, August 30 2010 at 9:57 AM

22. You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

# Posted By Security Community on Tuesday, August 31 2010 at 2:41 AM

23. Really impressed! Everything is very open and very clear explanation of the problems. It contains real information. Your website is very useful. Thanks for sharing. Looking forward to more!

# Posted By sell jewelry Houston on Wednesday, September 1 2010 at 2:41 PM

24.
Cheap nfl jerseys are your best choice, and retail nfl apparell and drop shipping are accepted as well. Grade cheap nfl sports jerseys,Competitive price and Best service, We do hope nfl jerseys usa to do long-term business with every clients and help you improvefootball jerseys more benefit from your market.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:29 PM

25. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:14 AM

26. As we all know, earrings are jewelry attached to the ear through a piercing in the earlobe or some other external part of the ear. Earrings are women's favorite. Proper Tiffany Bangles earrings can not only make a female look more beautiful, but also have the function of accommodating defects. Tiffany Cuff LinksSo it is necessary to know about how to wear earrings properly. Therefore, before you wear , you must take many factors into consideration, such as environment, your temperament, face shape, hairstyle, and your costume to reach the best effect.Wear Tiffany Accessories according to your face shape This will make your face look less plump. If you are long-faced, then you'd better choose Tiffany Sets hoop earrings or big earrings to make your face look more fetching. If you have a square-shape face, then dapper stud earrings, long drop earrings or exaggerated earrings can make you look livelier My discount silver tiffany
necklace
Blog.

# Posted By silver tiffany necklace on Thursday, September 2 2010 at 7:07 AM

27. how to get up and running with Story Driven Development with Rails.this article explain about this topic seriously. You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.
thanks

# Posted By fbf on Thursday, September 2 2010 at 2:56 PM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)