Story Driven Development With Cucumber

12,189 views

Published on

Software projects are rarely on-spec, on-time and on-budget, and the primary cause is miscommunication. As Martin Fowler says, there is a "yawning crevasse of doom" between stakeholders and developers, full of misunderstanding. How do you make sure that you're building something that adds value? How do you know you're building the thing that was asked for? How does your bottom line affect user experience?

Into the fray leaps Cucumber, a business-readable DSL combined with an awesome Ruby library that lets domain experts express business requirements as executable user stories. We'll cover outside-in, story-driven development with Cucumber, how to write effective stories, and how to make Cucumber work for your project.

(as given to CharlotteRuby on Jan 6, 2010)

Published in: Technology
1 Comment
13 Likes
Statistics
Notes
No Downloads
Views
Total views
12,189
On SlideShare
0
From Embeds
0
Number of Embeds
1,190
Actions
Shares
0
Downloads
166
Comments
1
Likes
13
Embeds 0
No embeds

No notes for slide
  • The root cause of so many problems in software projects is miscommunication.
  • This is largely because so much of software development is abstract - that is, it happens in your brain. Nontechnical people also have ideas and desires about what software can do that are equally abstract.
  • In the course of a project, it’s often hard to tell what’s really important to its success...
  • ...and who said what, and why you should care.
  • Bottom line, miscommunication is wasteful - in time, money, energy and relationships.
  • Miscommunication causes you to build the wrong feature...
  • ... or to build it incorrectly ...
  • ... or to build unnecessary features.
  • I bet you’re saying, “hey, aren’t you using an Agile process?” Why yes, I am, thanks. Agile methodologies have a few tools that we can use to help alleviate these miscommunication problems.
  • The first is user stories. For any feature that needs to be developed, you create a persona and write a story about how that person will use your software, and what things that person will want to accomplish.
  • Agile also gives us one of the top buzzes of the Ruby community since its adoption in the West- TDD. TDD encourages us to write tests for our software before we write the software, often resulting in better designs and greater flexibility as the project evolves. So what if we put these two techniques together?
  • When you do, you get what I call Story-Driven Development. Your agile user stories become the tests for your software. You’ll see more of what I mean in a little bit.
  • The focus of SDD is to keep your software lean and to create value with every new feature.
  • That is, at each step you’ll be doing the minimum to satisfy the requirements specified by the story...
  • ...and that story will be designed so that it directly affects your project’s ability to make new revenue, protect existing revenue, control costs, or alleviate user pain and increase utility (basically protecting revenue).
  • The path to finding the business value in each new feature is to pop the “why” stack.
  • That is, the person writing the story will query the business expert who is requesting the feature with pointed “why” questions until the result comes down to money. Along the way, you’ll identify who the stakeholders are and what value they receive. We’ll see more about how this fits into the process later.
  • By expressing the tests for your software first as user stories, you are greatly increasing the ability for the technical people to communicate with the business people. You start to develop a “ubiquitous language” for the problem your software addresses that will assist as the project progresses. See also Eric Evans’ “Domain Driven Design”.
  • With story-driven development, you can start to bridge Martin Fowler’s “yawning crevasse of doom” between the developers and the suits.
  • Your stories become a living functional specification and documentation for your software. Rather than requirements being handed down etched in a stone tablet, the stories become conversation pieces between all parties in the process -- customers, project managers, designers, and developers.
  • Furthermore, your user stories are executable tests that can be used to verify your software. Hooray for TDD!
  • So how can you implement this process in a Ruby project? You use Cucumber!

    Now what I’ve described before this point is 75% or more of what you’ll do in Story-Driven Development. Cucumber is just a tool to take you the last 25% from concept to implementation. So this next section is going to be a little more about the “how” and not the “why”. But first, more about Cucumber...
  • Cucumber’s first component is a business-readable DSL curiously called “gherkin”. This is a loose format for structuring your user stories so that they will easily translate to executable tests. Note that I didn’t say “business-writable”! The DSL is meant to be written by somebody who works with the biz person, but is also aware of the technical side.
  • Cucumber is also, unsurprisingly, a Ruby library that runs the stories as tests against your application.
  • Cucumber stories are intended to exercise your application from top-to-bottom, or more accurately, from the perspective of the user. So if you had to classify them, they’d be considered integration tests.
  • So here’s a pretty typical Cucumber story; this one happens to be about signing up to use the application.
  • The only portions of the story that Cucumber cares about are shown here in bold, so you’re pretty free to write the stories as make sense for the domain. “Scenario” signifies the beginning of a new story, Given/When/Then specify preconditions, user actions, and post-conditions respectively. You can also use “And” or “But” to make your story read well.
  • So let’s execute that story. Cucumber parses the story and attempts to run the Given/When/Then steps that we defined. Since we haven’t written any code yet, all of the steps are pending.
  • Now, you were probably wondering how we can implement one of those steps. Well, Cucumber gives us a hint whenever we have unimplemented steps. You can copy and paste any or all of those blocks out of the terminal into your favorite editor.
  • So let’s implement the first step. Given represents preconditions, so in this case, we’re just doing a paranoid check that there are no registered users. If this statement makes you uncomfortable, don’t worry just yet. Let’s run the story again.
  • Well, it failed, DUH! We haven’t defined the User class yet. So let’s go “down a gear” and implement what we need to make that step pass.
  • So, since this is a Rails app, we’ll use script/generate to create the User model and migrate the database.
  • Now if we run the story again, we see that the step passed. Before we did that, we might want to write some test/unit tests or RSpec examples to exercise our User model. However - remember we’re always trying to do the minimum amount possible to make the feature pass. If it wasn’t asked for, don’t build it!
  • So once you have created a step matcher, written what needs to be written to exercise the application, and filled in your lower layers of tests, you repeat that process until you get...
  • ... all green! At this point, you would pass the feature to other stakeholders who will evaluate and hopefully approve the work. But let’s first talk about some more of the features that Cucumber gives you that’ll make story-driven development a snap.
  • Every testing framework pretty much needs lifecycle hooks, and Cucumber doesn’t disappoint. You can define blocks that will be executed before or after each scenario, after each step, or applied to only specific scenarios or features you have tagged.
  • One feature I use a lot is to extend the Cucumber “World”, which is the object within which all of your steps execute. Just define a module and pass it to the global “World” method, and then the module’s methods will be available within any step or callback. There are quite a few plugins for Cucumber that use this technique.
  • So far, I’ve been speaking about how great this process is. But the ugly truth is that good user stories are really hard to write.
  • So how do you begin? You first write the value proposition. This is the most important part of your story and should answer why you need the described feature at all!
  • I start by writing “Feature:” and then a descriptive name for the thing that this story will describe, or a vertical aspect of the application that might not have a specific name -- for example, “Admin privileges”.
  • The next part is to “pop the why stack”, identifying the value in the feature. I usually write the value proposition in this three-line format, but there are no restrictions on how you write it. I just find that this format helps me focus on the business value of the feature.
  • So here’s an example from an app I worked on earlier this year. We identified the value, who would be taking the action in the story, and what the software would do to provide that value. This story describes a feature of an application for student goal and competency management in primary and secondary schools. [describe the value prop]
  • Next, I create a list of the various things the stakeholder/user can do. Each of these things becomes a scenario within the feature story.
  • Then you start formulating the scenario. The best way to do this is to write the outcome or “Then” step first, making sure that the desired outcome directly relates to the value proposition stated at the top. In this story, we want to manage school accounts, so seeing a list of the existing accounts would help toward that goal.
  • After you have the outcome, you decide what action the user takes to achieve that outcome, or the “When” steps. In this case, our user is navigating to the accounts page in our web app.
  • Finally, you write the preconditions for the user to be able to take that action, or the “Given” steps. We want this functionality only accessible to the site owner and not normal users, so we specify that the user must be logged in as the owner.
  • So how did I decide to write the story in that fashion? A good rule of thumb to use is that descriptive stories are generally better than imperative stories. Why?
  • You want to reveal intention. Your user doesn’t care about how the software is implemented unless they are directly affected.
  • Here’s an example from our previous feature of how descriptive steps and imperative steps differ. In the first we’re talking about a holistic action (WHAT), whereas in the second we specify the nitty-gritty detail (HOW).
  • Descriptive stories are more flexible than imperative stories. Why? The user interface of your software is the most brittle portion - you don’t want your whole suite of tests to break if the designer changes the wording of a single button, link, or field without changing the core functionality of the app.
  • However, you still need to strike a balance. It’s easy to be too vague and have a story cover huge swaths of functionality without intending it. Or the story might be unclear about which of several alternatives to take. Try to be descriptive without being ambiguous.

    Also, sometimes, especially early in the story-writing process, it’s a good thing to have imperative stories. When no code has written, when no design has been drawn, having that extra step-by-step may help flesh out more difficult details. You can always go back and rewrite those stories once everyone has a better grasp on the domain.
  • A common “story smell” in features are conjunctive statements. This is best illustrated in an example.
  • Conjunctive steps like the first one shown here tend to conflate two separate user actions. Independent steps, however, make the story more readable and the steps reusable within other stories. Remember that we’re trying to develop a ubiquitous language for our domain -- reusability is key to that goal.
  • Another “story smell” are multi-pass scenarios, or scenarios where multiple precondition-action-outcome groups occur. These are especially tempting to write if you are thinking imperatively about the problem.
  • The solution to multi-pass scenarios is to split them into multiple scenarios, or to abstract conditions and actions that are covered by another scenario. In this case, we’ve abstracted the concept of posting a comment, encompassing the steps the user took to get to that point. If you’ve already defined the offending steps for other stories, Cucumber lets you call them directly from within another step definition, so you can just subsume the steps that you want to abstract out.
  • Cucumber provides a few more features in the DSL that let you keep your stories terse and cover corner or edge cases efficiently.
  • In this slide I’m showing three of those features. The first is Background, which looks like Scenario, but is defined at the top of a feature file and applies to all of the scenarios in that file -- basically like a “Before” block with multiple steps. The second is a table - which you can access within the definition for the step before the table. You can treat the table as a simple array, or an array of hashes using the headers in the first row. The last feature is a multi-line string or “py_string” (as in Python).
  • Finally, we have Scenario Outlines, which are really great for quickly specifying scenarios across a range of possibilities, including edge or corner cases. Cucumber will run the outline against every row of the table that you specify in the “Examples” section, and apply the values in the table to the angle-bracketed items.
  • So, that’s the overview of Cucumber, and now here comes some shameless self-promotion.
  • You might have seen that little head in my second slide - which is from our app Lowdown. Lowdown is a collaborative story-writing tool for Cucumber that we created for the Rails Rumble last year, and we were lucky to win the prize for Appearance and User interface. I’d be willing to give a demonstration of Lowdown in the questions period.
  • Now that that’s over...
  • Do you have any questions?
  • Story Driven Development With Cucumber

    1. 1. Story-Driven Development with Cucumber Sean Cribbs
    2. 2. who am i • Freelance Web Consultant • Radiant Lead Dev • Ruby, Javascript, Erlang • Open-source contributor github.com/seancribbs
    3. 3. miscommunication
    4. 4. abstract
    5. 5. what’s important
    6. 6. who said what
    7. 7. miscommunication = waste
    8. 8. wrong
    9. 9. incorrectly
    10. 10. unnecessarily
    11. 11. “Agile”
    12. 12. user stories
    13. 13. Test-Driven Development
    14. 14. Story-Driven Development
    15. 15. stay lean create value
    16. 16. minimum to satisfy
    17. 17. make, protect, save money
    18. 18. pop the “why”stack
    19. 19. who are the stakeholders?
    20. 20. improves communication
    21. 21. bridge the crevasse of doom
    22. 22. living functional spec
    23. 23. stories = tests
    24. 24. http://cukes.info/
    25. 25. business-readable DSL
    26. 26. a Ruby library
    27. 27. integration tests
    28. 28. Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account When I signup with email and password Then I should be logged in And my profile details should be filled in
    29. 29. Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account When I signup with email and password Then I should be logged in And my profile details should be filled in
    30. 30. $ cucumber Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account When I signup with email and password Then I should be logged in And my profile details should be filled in 1 scenario (1 undefined) 4 steps (4 undefined) 0m0.754s
    31. 31. You can implement step definitions for undefined steps with these snippets: Given /^I do not have an account$/ do pending end When /^I signup with email and password$/ do pending end Then /^I should be logged in$/ do pending end Then /^my profile details should be filled in$/ do pending end
    32. 32. Given /^I do not have an account$/ do User.count.should == 0 end
    33. 33. Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account uninitialized constant User (NameError) ./features/step_definitions/signup_steps.rb:2:in `/^I do not have an account$/' features/signup.feature:7:in `Given I do not have an account' When I signup with email and password Then I should be logged in And my profile details should be filled in Failing Scenarios: cucumber features/signup.feature:6 # Scenario: Signup with valid email/ password combination 1 scenario (1 failed) 4 steps (1 failed, 3 undefined) 0m0.136s
    34. 34. $ script/generate model User email:string password:string exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/user.rb create test/unit/user_test.rb create test/fixtures/users.yml create db/migrate create db/migrate/20090912024901_create_users.rb $ rake db:migrate db:test:prepare == CreateUsers: migrating ========================= -- create_table(:users) -> 0.0016s == CreateUsers: migrated (0.0017s) ================
    35. 35. Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account When I signup with email and password Then I should be logged in And my profile details should be filled in 1 scenario (1 undefined) 4 steps (3 undefined, 1 passed) 0m0.136s
    36. 36. rinse and repeat
    37. 37. Feature: Standard Signup In order to begin using the application As a new user I want to create an account Scenario: Signup with valid email/password combination Given I do not have an account When I signup with email and password Then I should be logged in And my profile details should be filled in 1 scenario (1 passed) 4 steps (4 passed) 0m0.138s
    38. 38. Before do # do before each scenario end After do # do after each scenario end AfterStep do # do after each Given/When/Then/And/But step end Before("@tagged") do # do before scenarios tagged with @tagged end
    39. 39. # features/support/time.rb module TimeHelpers def set_zone(zone_name) Time.zone = zone_name end end World(TimeHelpers) # features/step_definitions/user_steps.rb Given /^I am in the "([^"]*)" time zone$/ do |zone| set_zone(zone) end
    40. 40. good stories are hard to write
    41. 41. start with the value proposition
    42. 42. Feature: Name or theme
    43. 43. Feature: Name or theme In order to make, protect, or save money As a stakeholder I want to have some feature
    44. 44. Feature: School account management In order to maximize revenue by offering our product to multiple schools at once As the site owner I want to provide individual accounts to each school and manage them
    45. 45. Feature: School account management In order to maximize revenue by offering Schoolbinder to multiple schools at once As the site owner I want to provide individual accounts to each school and manage them Scenario: List accounts Scenario: Create an account Scenario: Revoke an account Scenario: List admin users for accounts Scenario: Change subdomain for account
    46. 46. Feature: School account management In order to maximize revenue by offering Schoolbinder to multiple schools at once As the site owner I want to provide individual accounts to each school and manage them Scenario: List accounts Then I should see a list of accounts
    47. 47. Feature: School account management In order to maximize revenue by offering Schoolbinder to multiple schools at once As the site owner I want to provide individual accounts to each school and manage them Scenario: List accounts When I go to the accounts page Then I should see a list of accounts
    48. 48. Feature: School account management In order to maximize revenue by offering Schoolbinder to multiple schools at once As the site owner I want to provide individual accounts to each school and manage them Scenario: List accounts Given I am logged in as the site owner When I go to the accounts page Then I should see a list of accounts
    49. 49. descriptive > imperative
    50. 50. intention > implementation
    51. 51. # descriptive When I create a new account for "ms218" # imperative When I follow "New account" And I fill in "Name" with "ms218" And I submit the form
    52. 52. descriptive stories are flexible
    53. 53. strike balance too implicit = vague
    54. 54. avoid conjunctive statements
    55. 55. # conjunctive When I change my name to "Sean" and my password to "foobar" # independent When I change my name to "Sean" And I change my password to "foobar"
    56. 56. strive for single passes
    57. 57. # conflated scenarios, multiple passes Scenario: Bulk comment on short term goals Given I have set all short-term goals for "ELA > Writing > Organization" for class "601" When I follow "Edit" for long-term goal "Organization" And I follow "Comment" for short-term goal "Coherence" Then I should see all students that pertain to this short-term goal And I should see the standard comment box and "Post new comment" button When I type in the comment box And I follow "Post" Then I should see that my comment was posted # single scenario, single pass Scenario: Bulk comment on short term goals Given I have set all short-term goals for "ELA > Writing > Organization" for class "601" When post a comment for short-term goal "Coherence" Then I should see that my comment was posted And all students in class "601" should receive my comment
    58. 58. stay terse cover corner cases
    59. 59. Background: Given an account for subdomain "ms217" And these administrators for subdomain "ms217": | email | name | | joe@ms217.edu | Joe Smith | | jane@ms217.edu | Jane Doe | And this welcome message for subdomain "ms217": """ Welcome back, students! - The principal """
    60. 60. Scenario Outline: Successful authentication with email Given a <type> named "<first name> <last name>" with email <email> and password "<password>" And I am on the login screen When I login with "<email>" and "<password>" Then I should be logged in Examples: | type | email | first name | last name | password | | student | joe@school.edu | Joe | Smith | testing123 | | teacher | jane@school.edu | Jane | Brown | testing456 | | staff | mark@school.edu | Mark | White | testing789 | | admin | paul@school.edu | Paul | Greene | testing098 |
    61. 61. <self:promotion>
    62. 62. </self:promotion>
    63. 63. questions?

    ×