Going Outside In with Rails, Cucumber, and RSpec

March 28th, 2009 by admin Leave a reply »

Traditionally when you do emergent design, at least in my experience, you go from the inside out. Work from your model into your controller and views. Since web applications are so heavily focused on user interaction it sometimes is better to work from the outside in. When working with a Rails application think instead of your views and work into your controller and models.

Understand the UI first before you write any code. Use things like paper prototyping to understand real user data needs and challenges. Paper prototyping is a cheap and easy way to understand what objects and data a user will be interacting with for a given task. Keep your session short, and focus only on the feature you’re developing. You can find examples of paper prototyping on YouTube.

Get boot-strapped with Cucumber, RSpec and RSpec-Rails, and dive straight into BDD on your Rails project. To do this you need to install various gems to support your development efforts:

sudo gem install cucumber rspec-rails webrat
cd my_rails_project
script/generate cucumber
script/generate rspec

That’s all you have to do to get going! You’ll notice that you’ll have a new features folder and the usual spec folder (from RSpec). You will want to describe your features as stories and scenarios for Cucumber in the features folder. Start with your views when you think about scenarios.

The basic gist of it is just like regular TDD, except we are focusing on behavior:

  1. Choose a single Cucumber scenario
  2. Create a failing step definition in Cucumber
  3. Create a failing spec in RSpec
  4. Write code to make the spec pass (red/green refactor)
  5. Repeat 3 and 4 until the scenario is passing

In the process of making the scenario pass you’ll find yourself discovering models and controllers that will need to be written or updated. Taking this type of approach helps you focus on writing just enough code to get your tests passing, without over engineering, and has the added benefit of you writing testable code. (Remember TDD/BDD is not so much about testing as it is about communication, documentation and design!)

Your finished scenario should touch a complete vertical slice of your application, that is to say, model->controller->view. It should provide some real value to the user. Agile development philosophies frown on partial feature delivery. A schema, security filter or screen alone is not a feature. If you write scenarios from the user’s perspective you’ll avoid this pitfall.

To learn more about Cucumber and RSpec (either in Rails, or plain Ruby) I would recommend checking out Pragmatic Bookshelf, they have a beta book on RSpec.

Advertisement

Leave a Reply