Features for a Resource

April 07, 2009

REST is great, and resources are a great design tool. If we design our rails application around resources we can get alot of things for free. If we apply the same idea to features can we create a standard set of features to give us a quick start for each resource we identify?

Resources - Object and Collection

With standard rails routing we will get various named routes which we can use either directly in our features or indirectly in our step definition

For example if our routing table has

     new_admin_product GET    /admin/products/new
 destroy_admin_product GET    /admin/products/:id/destroy
    edit_admin_product GET    /admin/products/:id/edit
         admin_product GET    /admin/products/:id

              products GET    /products
               product GET    /products/:id 

Then we can easily write

When I view products

and match this with

When /^I view product$/ do 
  visit products_url
end

In a similar way we can do things like

Given there is a product with name widgit
When I view the product

matched with

Given /there is a product with name (\S+)$/ do |name|
  Product.generate!(:name => name)
  @x = Product.find_by_name(name)
  @x.should_not be_nil
  @x
end

When /^I view the product$/ do 
  # use the variable x from above
  visit product_url(@x)
end

Its fairly straightforward to extend these features and steps to match the other actions, and with a bit of ruby and regex fu we should be able to generalise these features so we can use them with any resource

Resource Views

The simplest way to do this is to use CSS classes. I take this approach because it is robust. Object are represented in a div with the singular name as a class and collections use the plural. e.g. in Haml

.product 
  product details go here
  
.products
  list of products go here

Resources - Info (A Basic Data Definition)

I think it might be a nice idea to describe a resource on its list page using some text in an div#info. e.g.

#info
  Products are things that we actually sell. They come from wholesale_products which are supplied to us.
.products

This is just a little convenience which will be replaced/hidden when we start doing specific work with the resource.