Cucumber Scenarios – Redux

Back when I was a BDD n00b I had dwelled into different styles of writing Cucumber Scenarios here. After six to seven months of usage and reading The Cucumber Book by Matt Wayne, things are lot more clear than what it was then.

In this post I want to bust some misconceptions about Cucumber and shed some light into the way it needs to be used.

What is Cucumber?

First let us understand what Cucumber really stands for in the BDD eco-system. The book definition is like this –

Cucumber is a tool that facilitates discovery and use of a ubiquitous language within a team.

This understanding of Cucumber is critical before we jump into writing Cucumber Scenarios. It’s a tool for unearthing language of the domain and there by facilitating an understanding of the domain.

It’s primary focus is not an Integration Test Tool or worst an Unit Test Tool. In the end of it if it can help in catching Regression issues that is the happy side effect of using Cucumber.

Since the idea of Cucumber is to find the ubiquitous language of the domain, the Cucumber scenarios need to be worded carefully so that it makes lot of sense to the technical and functional teams. Cramming lot of technical details (like UI details) is not a great idea while coming up with scenarios. Cucumber scenarios goes on to become the living documentation of the system.

Declarative or Imperative?

Imperative Style

Scenario: Open Account
Given I am in new account page
When I fill in Name with "Arun"
And I fill in DoB with "25/1/89"
And I select "Male" from "Sex"
And I press "Submit"
Then I should see "Account created."

Declarative Style

Scenario: Open Account
Given I do not have an account
When I sign up for an account
Then my account has to be created

As evident from the two scenarios, imperative one is tied up to the UI implementation of the system. It doesn’t really reveal the intent of the scenario properly. The declarative one on the other hand is really working at
an abstract level and probably communicates well to both functional and technical people. The declarative style clearly reveals the intent more succintly to the reader.

Other problems inherent with imperative style is maintenance, a slight change in UI like change of button caption will lead to change in the Scenario definition itself, which seems not right because your domain hasn’t changed to ensue a change in the Ubiquitous language of the domain.

Outside-In Development

Early days of BDD I was under the misconception that outside-in development means we have to drive out our design from UI, then drill down to controller and models. That was just a stupid understanding from my
side. Later I realized it was just meant to say Outside of what we want to discover. So it is perfectly fine to use Cucumber first to build the Domain Model layer of the system and later build UI on top of it.

Courtesy : The Cucumber Book

As shown in the figure (courtesy: The Cucumber Book) above, it is perfectly valid and sensible to run your Cukes on top of the domain model and then switch to full blown integrated system. So in the first few days, probably you will be driving out the design on Domain Layer from Cucumber and once it is done you can step into building the UI on top of it.

The switch from Domain to UI would entail a change Cucumber support code to point to UI (through Capybara) to make the Scenarios pass.

The point to realize is that when you move from Domain Model to UI Layer the language of your scenarios are not changing it remains same.

Pitfalls & Myths

Cucumber is hard to maintain

Yes they can be extremely hard to maintain if you go by the imperative route. A small label change in UI will break scenarios. Lately I had met many Ruby developers in Agile Conf & Ruby Conf India, and the common rant against Cucumber was it was hard to maintain.

I am really not sure if you do Cucumber in Declarative Style will it lead to maintenance problems or not? Declarative style reveals us the understanding of the domain. Now if the domain itself changes, then your code has to change, your tests have to change and so your Cucumber Scenario has to change. I cannot quite clearly see how maintenance problem creep in if Cucumber is used the proper way it is meant to be.

Writing Imperative Style

If you intend to write Imperative style cucumber scenario then the best place to do that will be RSpec Integration Tests and not in Cucumber.

Picture this

When I fill in "Name" with "Arun"
When I press "Submit"

can also written in same readable way in RSpec as

fill_in :name, :with => "Arun"
click_button "Submit"

And other places where imperative style creeps in is

And I press "Submit"
Then I should be on account page
And I should see "Arun"
And I should see "25/01/1989"
And I should see "Male"

Here we are testing UI elements using elaborate Cucumber Scenarios. Probably the best place for this code to live is RSpec View Tests.

Such test add overhead to maintenance and do not promote any readability for the stakeholders. Worst it doesn’t help in arriving at the ubiquitous language of the domain.

Pushing Unit Tests to Cucumber

This the case of overusing Cucumber without relying on Unit Tests. Consider the Scenarios below

Scenario: Create Account
Scenario: Create Account without Name
Scenario: Create Account without DoB
Scenario: Create Account without Name & DoB

Probably difference in these Scenarios may be the flash message which gets displayed. There is no need for all such trivial variations sitting in Cucumber, instead the last 3 scenarios can be pushed to the RSpec Model or even Controller layer and Cucumber can be left with Create Account scenario in Declarative style alone.

Remember writing Cucumber is not an excuse for not writing RSpecs. Cucumber creators themselves heavily advocate to use Unit Tests when we drill down from failing cukes to domain layer.

Bloated Step Definitions

The Step Definition file needs to be maintained cleanly without cramming in lot of code into that. Each step definition should delegate to the Cucumber support layer through a neat DSL. One of the good things if you follow this strictly is that at the end of cycle you will be able to arrive at a clean DSL for your domain.

For example

Given /^When I sign up for an account$/ do
  sign_up :name => "arun", :dob => "25/01/1989"
end

As you can see in Step Definition it just call for a sign_up method, here we are not putting Capybara Steps or Model interaction code directly.

sign_up method can live independently in support layer inside a module like AccountDSL.

module AccountDSL
  def sign_up(params)
     visit new_account_path
     fill_in :name, :with => params[:name]
     fill_in :dob, :with => params[:dob]
     click_button "submit"
   end
end

So the UI interactions are localized into the single method. And the Step Definition can be reused any where within multiple scenarios. Even if a UI redesign happen you need to bother only about changing AccountDSL::sign_up method.

Also before we got into the UI building, we might have worked with same scenario interacting directly with Domain Layer. At that point probably the sign_up method would have read like this

module AccountDSL
   def sign_up(params)
     Account.sign_up(params)
   end
end

Once the UI is ready it is just the question of swapping the implementation of sign_up method.

Summary

As they say Sign of well-written specs: the –format documentation gives a nice summary of all the project features to any stakeholder (link).

Sign of well-written Cucumber Scenario is to promote understanding of the domain and to derive an unbiquitous language of the domain.

Emacs absolute basics

There is an awesome editor out there which are used by great programmers and then there is an OS which is also getting used as an editor by the not so geeky🙂

Hugely inspired or copied from Vim Katas


I will write a line and hit C-j to insert a new line
I will write a line and hit C-a C-j to insert a new line above

I will navigate from beginning of line to end of line using C-a and C-e
I will go to the top of the document by hitting M-<
I will go to the first line of the document using M-g g 1
I will go to the thirty fifth line of the document using M-g g 35
I will delete the first line by using M-< C-k
I will paste it back using C-y

I will delete the next line using C-n C-a C-k
I will delete the entire line using C-S-backspace
I will paste it back using C-y
I will repeat previous command using C-x z

I will undo using C-_
I will undo again using C-_

I will select a line using C-a C-SPC C-e
I will remove everything using C-w
I will undo using C-_

I will go down a line using C-n
I will go up a line using C-p
I will go left 1 using C-b
I will go right 1 using C-a
I will go up four lines using M-4 C-p
I will go up four lines using C-u 4 C-p
I will go up four lines using C-u C-p
I will go down four lines using M-4 C-n
I will go down four lines using C-u 4 C-n
I will go down four lines using C-u C-n
I will go down eight lines using C-u C-u C-n

I will select 2 lines below this using C-n C-a C-SPC C-u 2 C-n
I will select 4 lines below this using C-n C-a C-SPC C-u C-n
I will select 3 lines above this using C-p C-e C-SPC C-u 3 C-p

I will save using C-x C-s

I will navigate by word using M-f
I will navigate by many words using C-u 3 M-f
I will replace words using M-%
I will undo those changes using C-_
I will delete this line using C-S-backspace and undo with C-_
I will delete these words using C-u 3 M-d
I will undo using C-_
I will save and quit with C-x C-c

Agile Tour Visits Hyderabad

For the first time Agile tour visited Hyderabad last weekend on October 1st. The event was held at the awesome HICC.

This event comes in the back of Agile Hyderabad 2011 conference which was a well organized one and had great speakers like Vibhu Srinivasan and Jesse Fewell.

The theme for Agile tour Hyderabad was Agile First Steps. As the theme indicates, the conference delved into the basics of Agile, especially the “what” bit — understanding what agile is and what benefits it provides. Understandably, the talks didn’t venture much into the “how” of it. On a personal note, it was a little disappointing to have such a theme as I was pretty much comfortable with the basics of Agile after reading books on Scrum, Extreme Programming, Lean Software Development and of course practicising xDD and little bit of Scrum. But I was also looking forward to meet the agile community in Hyderabad.

The event kicked off with a key note by Mr. Vivek Jain, Director, Pega Systems, on “Introducing Agile Work in a Product Enterprise”. Basically the talk was about how Pega System adopted Scrum and have seen exponential growth in revenue numbers and have successfully launched a couple of products after that. They had adopted Scrum hardly 2 years back after doing waterfall/chaotic model for a decade or long. The talk was well delivered but I have a peeve for the way it was delivered. I thought they spend lot time explaning Pega Systems, their revenue and market analysis etc. rather than focussing more on nitty-gritties of how really Scrum works at the ground level or at least what their experience has been.

Then we moved to the 2nd key note of the day by Madhur Kathuria. Madhur is the only Certified Scrum Coach in India, and I have heard him talk at Agile Hyderabad 2011. He is an eloquent speaker and really engages the audience well in his talks. So I was expecting a very good session and Madhur really delivered with his keynote on “Why it’s hard to Scrum in India”. He touched on the cultural factors which stand against us (Indians) when it is coming to do Scrum. I still remember the points he delivered on that day on top of my mind. I think some of the factors he touched upon were

  • The Cultural Factors – where we Indians hesitate to say NO
  • Chalta Hai Attitude & Jugaad – basically we tend accept status quo and just accept to fate “it’s like that only”
  • The Service Focus – where we accept anything that client tells us to do blindly
  • The Power Index – where the perceived distance to power center is pretty large when it comes to Inida.

Overall Madhur did a great job and by interspersing games between the talks and there by engaging all the participants the session received a good response.

After the keynote was the time for Just a Minute sessions where anyone can walk up to the stage and talk for a minute or two about their pet topics. I talked about the lack of focus on Engineering Practices in Scrum, especially in Indian context how bad it may hurt the success of agile projects. The message I was trying to drive was – even if we do Scrum, do standups and plan our sprints etc. if we are bad at writing code, if we do not do proper TDD, Refactoring, Continuous Integration and so on, we are basically just sugar-coating our old bad habits with the guise of Scrum and in a couple of years down the line we could be staring at a system which would be tough to maintain, enhance and understand much like the Big Ball of Mud. Weren’t those the problems which waterfall had and agile tried to solve when it came to limelight in the early 2000s?

Here is a picture of me doing my JAM session.

Arun's JAM

The next 30mts was for Open Space where, any one could propose a topic and whoever interested in topic can form a group and discuss the same. There were around 8 topics up for discussion. I participated in topic “TDD” and had some heated debate with my fellow participants and I also propsed and anchored a topic on “What killed waterfall could agile”. Again it was based on my JAM talk about lack of engineering focus while practicing agile. The ideas were around lack of learning in technical side from Project Managers, lack of passion to improve by the upcoming developer community in India and of course the attitude that “if it ain’t broke, don’t fix” which is dangerous! And here is why, quoting from the Refactoring Workbook:

Build Testing into Your Practice

There’s an old adage (as so many are), “If it ain’t broke, don’t fix it.” (How many times has that last simple change caused an unexpected bug?) In programming, the downside of applying this adage is that the code just gets uglier and uglier.
Refactoring is willing to go against this rule through two mechanisms: safe refactorings and a supply of tests to verify that the transformations have been done correctly. Don’t neglect your tests.

In fact resonating my idea Jesse Fewell has touched upon the same topic in his latest blog past about his experiences with India. Read the section India’s talent is an impediment. Sad, but true!

The afternoon sessions were split into two tracks and I had a chance to attend the following topics

Learning Agile by Flipping Pennies, by Tushar Somaiya – the idea of the session was simple, there was a team of 4 (requirements guy, design guy, coder, tester) and their respective managers. The team had to flip a bunch of different coins based on some value assigned. First it was done in waterfall way, then it was done in a more iterative way with smaller releases and focussed priorities. After each round the timings were noted and we were shown how agile really reduced the time to market and how effectively people were engaged rather than sitting idle.

Culture and it compatibility in Agile Adoption, by Mohammed Shaik, PayPal – Shaik really spoke well from his experience of 10+ years on what sort of org culture works for Agile and what doesn’t work. He was really forthright in pointing out the short comings of Agile Projects being done in India and how they were just doing lipservice in the name of Agile.

Scrum and Lean: Multiply the Powers, by Om Band, SAP Labs – He demonstrated how SAP had adopted lean practices and meshed it with Scrum and using it in their day-to-day work. I thought this was the best session I attended, it really concentrated on the meat instead of focussing on SAP. The explanations of Lean principles were crisp and to the point. I really enjoyed this session, more so because I am very keen in Lean Startup concept as well.

Master the how, not just the what and why in Agile world, by Shweta Parashar, Xebia – This was a game of building Lego House using Scrum methodology. There were 3 teams of 7 members and each team had Scrum Master. We planned on the Back log, Sprint Plans and Sprint Tasks embarked on building the house by picking task by task. There was also a scrum board on which we posted our tasks using sticky-notes, and moved them from “To Do” to “In Progress” to “Done” time to time. I think the time given for the session was not enough to complete the task or the task was big (probably they could have chosen a less complicated lego toy), nevertheless it was an enjoyable experience. I thought even the presenters were doing it the first time and generally the teams struggled to build the house because there were a hell of a lot of pieces to be arranged. Our team did a fairly decent job, and only we could build something which was appreciated by our Product Owners (aka presenters). Perphaps my experience of playing with my son daily using blocks and lego toys helped us😉

Overall

Yea, the cookies were real good, food was awesome, and the desserts were fabulous😉

Coming to the sessions, as I said it was at a very basic level. So if you were aware of Agile Methodology and its basics there was nothing much to take home as learning — it was just reinstating the points back. Again more of it was tuned towards corporate audience in well-set companies (read Project Managers). As a Startup founder may be many of these points may not be applicable for my situation. But looking at the audinece profile, most of the members were Project Managers who never had done Agile in full spirit, they were also trying to figure out how things worked in Agile and many were confused whether what practice they were doing in their job was Agile or not. I could see that there were many misconceptions and misunderstanding floating around. Like one guy concluded that Waterfall with shorter iterations is Agile, or some one else was saying that they did TDD, where they documented the test-case in a Word Doc before starting coding or a Project Manager was mentioning how Agile reduced their release cycle from one year to 6-7 months.

And adding to the list is my pet peeve the target audience was just Project Managers not developers for this conference. I really hope that they had one track next year as to how they do agile technically as well like how you practically do TDD with xUnit or how you refactor the code and stuff like that sort. Again I may be wrong because in Indian context only managerial stuff may sell.

But overall I would rate the event was very good, it gave opportunity to meet a lot of people and surely I hope Agile Tour would come up with a big bang next year as well.

Some of the links from the event
http://www.facebook.com/media/set/?set=oa.267944886569832&type=1
http://www.isec.co/event_detail_info.php?event_id=5

Tidying up your RSpecs – 1

This is a cross post from our company blog.

Almost everyone in Ruby world agrees that RSpecs are a great way to test code in both Ruby and Rails projects.

Today, I want to share some of the tips which I had learnt and used in my RSpecs which has really help to tidy up the RSpec code and output.

Explicit Subjects & Contexts

Consider a RSpec for a Rails Controller. Assume that controller actions require a user to authenticate himself before performing any of the actions. In order to test this aspect we can write RSpec like this

describe PlacesController do
  describe "access control" do
    describe "for non-signed in users" do
      it "should redirect to sign in page for delete :destroy" do
        delete :destroy, :id => "1234"
        response.should redirect_to(new_user_session_path)
      end
      it "should redirect to sign in page for get :index" do
        get :index
        response.should redirect_to(new_user_session_path)
      end
      it "should redirect to sign in page for get :show" do
        get :show, :id => "123"
        response.should redirect_to(new_user_session_path)
      end
    end
  end

The above specs can be repeated for each and every action in the controller. Now when I run the above spec the output will look something like this.

for non-signed in users
  should redirect to sign in page for delete :destroy
  should redirect to sign in page for get :index
  should redirect to sign in page for get :show

The output doesn’t read really that great. One of the good guideline which I believe for writing good RSpec is that the output should be really readable like a prose and easily convey the behavior or intent of the code it tests. So it’s time to tweak the code and make the output more readable. Also if you look the code has lot of repeatition of response.should redirect_to all over the place. So let us clean up that with explicit subject and context.

describe PlacesController do
  describe "access control" do
    context "for non-signed in users" do

      subject { response }

      context "delete :destroy" do
        before { delete :destroy, :id => "1234" }
        it { should redirect_to(new_user_session_path) }
      end

      context "get :index" do
        before { get :index }
        it { should redirect_to(new_user_session_path) }
      end

      context "get :show" do
        before { get :show, :id => "123" }
        it { should redirect_to(new_user_session_path) }
      end
    end
  end
end

Notice how I have used the subject {} to specify an explicit subject. The implicit subject for any RSpec is the class which is used with the describe at top. In the above case it would be PlacesController. By specifying an explicit subject we are declaring the object which need to evaluated for subsequent tests. In this case it has been set to the response object. The usage of context really makes the code much clean and readable. Basically it sets the context for each test case while running. Now if we run the RSpec the output looks much cleaner like this.


for non-signed in users
  delete :destroy
    should redirect to "/users/sign_in"
  get :index
    should redirect to "/users/sign_in"
  get :show
    should redirect to "/users/sign_in"

Here is another example of an explicit subject below. This is an RSpec for User Role assignments with CanCan.


describe Ability do
  context "Admin Role" do
    before(:each) do
      @admin = Factory(:admin)
      @ability = Ability.new(@admin)
    end

    subject { @ability }
    it { should be_able_to(:manage,User) }
    it { should be_able_to(:manage, Restuarant)}
    it { should be_able_to(:manage,Place) }
  end
end

The code really is looking succinct and clean with the usage of subject {} . Without the subject it would have been a drudgery to write the same piece with describe…it..end blocks.

Shared Examples

Now let us turn our attention to the technique of Shared Examples which keeps our RSpec code DRY. Here is an example which tests the Links appearing in a footer of the page based on the User Role.

shared_examples "footer" do |links|
  links.each do |link|
    it "with #{link}" do
      within("div#footer") do
        page.should have_xpath("//nav/ul/li/a[contains(text(),'#{link}')]")
      end
    end
  end
end

describe "Footer" do
  extend LinkHelpers

   context "not signed in user" do
    before { visit search_home_path }
    it_behaves_like "a footer", normal_links
   end

   context "Admin" do
     before(:each) do
      @admin = Factory(:admin)
      sign_in_user(@admin.email,"password")
     end
     it_behaves_like "a footer", admin_links
   end
end

The code is pretty self-explanatory. For a noumal user I want a bunch of links to appear in the footer. For an admin user I want another set of links to appear. In the code above normal_links method gives the array of links for normal user and admin_links gives the array of links for admin user. [Note normal_links and admin_links are methods defined in a module LinkHelpers which I am extending below describe]

Coming to the DRY part. The code for doing the actual testing is put under a shared_example “footer” and it is invoked with it_behaves_like call. Also note we can pass zero or any number of arguments to shared_example. In the example above it accepts a single argument of Array type.

Let us see the output of the above code:

Footer
   not signed in user
     behaves like a footer
       with About Us
       with Feedback
       with Disclaimer
   Admin
     behaves like a footer
       with About Us
       with Feedback
       with Disclaimer
       with Manage Restaurant
       with Manage Place

Even though the behavior and output is correct, the above results and code doesn’t read proper. Probably we shouldn’t call display of footer as a behavior. RSpec to rescue again! We can customize what appears in the output (in this case “behaves like a”) as well as rename the function it_behaves_like to something which is more appropriate for the context.

So for diplay of a footer it may be good to have a function like it_has_a “footer” instead of it_behaves_like “a footer”. Now let us see how this done:

RSpec.configure do |c|
   c.alias_it_should_behave_like_to :it_has_a, 'has a'
end

shared_examples "footer" do |links|
   links.each do |link|
     it "with #{link}" do
       within("div#footer") do
         page.should have_xpath("//nav/ul/li/a[contains(text(),'#{link}')]")
       end
     end
   end
end

describe "Footer" do
   extend LinkHelpers

   context "not signed in user" do
     before { visit search_home_path }
     it_has_a "footer", normal_links
   end

   context "Admin" do
     before(:each) do
       @admin = Factory(:admin)
       sign_in_user(@admin.email,"password")
     end
     it_has_a "footer", admin_links
  end
end

In the above code RSpec.configure block actually aliases the it_behaves_like function it_has_a and specifies that “has a” should be the output instead of “behavies like a” while the specs are run. Let us check the output now:


Footer
   not signed in user
     has a footer
       with About Us
       with Feedback
       with Disclaimer
   Admin
     has a footer
       with About Us
       with Feedback
       with Disclaimer
       with Manage Restaurant
       with Manage Place

To Conclude

  • Use context with describe and make the test more readable instead of just getting stuck with describe..describe…it kind of format.
  • Give a before {} block for any context to set any pre-conditions before running the context.
  • Wherever possible declare an explicit subject and reduce the cruft in the specs.
  • DRY up your RSpec with shared_examples.
  • Customize the method name and output by aliasing in RSpec.configure.

Hope this post was helpful, do share your thoughts if any!

Treasure [Witch] hunt at Sree Padmanabha Swamy Temple

The great hunt is on and each day crores of value worth antiques are unraveled from the hidden chests and dark chambers of the great Sree Padmanabha Swamy Temple. Its really mesmerizing to read all about the treasure and its hidden coffers in such an ancient monument and engineering marvel.

South Indian temples really fascinate me, its grandiose structure and innate work and fine grained artistry really entices me. These temple just shows the passion of people who conceived this structures and passion of people who worked for them to make it as they are – a resilient structures which can withstand 1000 years of time and tide.

Sree Padmanabha Swamy temple is relatively a young temple compared to great Chola or Pallava monuments in Tamil Nadu. The great temples in Tanjore, Chidambaram, Gangai Konda Cholavaram, Kumbakonam really bowl me over when I stand before them like a kid with eyes and mouth wide open.

Its really no surprise that so much of treasure is hidden beneath the stone structure of Padmanabha Swamy temple. In fact each and every ancient temple in South India surely would have had such secret treasure troves, but alas now everything is lost because either being looted by British or invading Muslim Kings and if they have survived those stooges our own people might have siphoned off them. The crux is we Indians don’t take pride in such structures nor do we care about these marvels. Many people loathe going to temple for various reason – being an atheist or aversion to crowd or laziness to travel and many other silly reasons. No wonder in Chidambaram you see lot foreigners with cameras than Indians with camera. They are fascinated by them than us.

Coming to this unraveling story of treasures in Padmanabha Swamy Temple – what will happen to them? Now that secret is out in the open vested interests in different quarters may be frothing in their mouth to take control of temple or to seize a nickel out of it and keep it in their showcase or worse siphon it off for money. Remember the price being derived is just based on current market rates, if you add the antique value of these pieces it may run into more crores in value. But it would also be insane to argue that these whole thing is proprietary of one family now. These treasures are not earned by them, they might have been got as gifts to the state, as tax and wealth of the state. So today a family cannot come and claim them because of a lineage. Its like our Prime Minister claiming rights on India’s economy. I feel it belongs to the people of Kerala and its upto the people be proud about it, be passionate about it and care about it and preserve it for generations.

Sree Padmanabha Swamy temple is one of those finest temples out there where a visit can really calm your soul and soothe you. Its ranks high in the way its maintained and run. A big kudos to the Royal family and the trust which does it – after all they never got tempted to loot the treasures till now. Alas that today we have denigrated to such a passé that arbid ego clashes and petty interests have lead to this skull drudgery of a situation and we have no one to blame but ourselves [read Hindus] for such an impasse. From here if an ordinance is promulgated and secular Congress party decides to put a secular person [like Mr. George Joseph or Mr. Mohammed Haji] in the trust running the temple we just have to live with it.

Now the question is next what? What to do with the treasure – should we use it for eradicating poverty or negating some of our fiscal deficit or implement NREGA with that? Anything can happen in this country. I am sure some insane voices would opine that now that people know about the treasures they are not safe where they are and should be put in bank vaults. Nothing can be disastrous than that. We have smart people in this country who even though cannot be creative can easily be creative enough to make fakes and swap the real ones. Hope we won’t tread that path. I personally would like them to maintained where they are and status quo maintained on it. Or even if they can make some great fool-proof arrangement to exhibit them and open the chambers for public that would also be good (something like public viewing every year say, for 2 weeks and then they are back to the chambers). I personally would like to see them and more than the treasure I would be excited in seeing the secret chamber and its security plugs.

Its not clear as to what will happen to the temple or the treasures – a handful of cronies and their ego will decide its fate. But thank god they can’t take the Lord away or take the shrine itself away. Those two are enough for mere mortals like me to be happy about.

A walk in the alleys of this sacred temple is enough to transpire you to another realm, to mesmerize you about our rich history and culture and hope a day will not come when they won’t even allow to do that!

Rails HABTM in Mongoid & Factory Girl

In Rails say you have a HABTM (N:N) relationship between two models


class User
has_and_belongs_to_many :posts
...........
end

class Post
has_and_belongs_to_many :users
.......
end

So what essentially it means is a Post can have many Authors and an Author can have multiple posts.
Now you want to test drive the thing by seeding test data in Factory Girl.

Here is an article for seeding data for 1:N relationships in Factory girl. But it doesn’t talk about HABTM relations.

I was playing around with factory girl and figured out a way to seed a post with authors.
Here is how you do it –


Factory.define :user, :class=>User do |user|
user.first_name "Alex"
user.last_name "Malcolm"
user.nick_name "Alexy"
user.email "alexy.m@gmail.com"
user.password "foobar"
user.password_confirmation "foobar"
user.role "author"
end

Factory.define :post do |post|
post.title "Foo Post"
post.content "Bar content"
end

Factory.define :post_with_author, :parent => :post do |post|
post.after_create { |p| Factory(:user, :posts => [p]) }
end

Now in your Test class do
@post = Factory(:post_with_author)

Factory girl would have inserted the User for you and then a Post and updated the relationship.

Btw I the code above was tested in Mongoid/MongoDB and not on Active Record. But since its working in Mongoid there is no reason I see why it won’t work with Active Record natively.

Another thing which I found with Mongoid/MongoDB and HABTM is that unlike Active Record you don’t need a Join Table like Users_Posts – the reason being MongoDB doesn’t support join queries. So you have to lump the join table into the respective models.

The Mongoid stores HABTM relation in back-end something like this

> db.users.find()
{ "_id" : ObjectId("4dc2010ea38c3d0b50000003"), "first_name" : "Alex", "last_name" : "Malcolm", "nick_name" : "Alexy", "post_ids" : [
ObjectId("4dc2012fa38c3d0b50000005"),
ObjectId("4dd1240ca38c3d104a000009"),
ObjectId("4dd12ff9a38c3d104a00000f")
], "role" : "author" }

That is in the Users model you have an array of post_ids and similarly in the Posts Model you will have an array of user_ids.

And finally if its on Active Record it may be preferable to have has_many :through instead of has_and_belongs_to_many relation as this post says.

Cucumber Scenarios : The Dilemma

Off late I am exploring BDD with Cucumber & RSpec in Rails.

The first step in BDD after understanding the customer requirements is to come up with the User Stories in a particular structure. Read this brilliant article from Dan North if you want to know more on the structure of User Story in BDD.

Let’s say I am creating a simple blog app, a sample Scenario for Creating a Post can be written in two ways as shown below. These scenarios are as coded for Cucumber.

A pithy way

Scenario: Create Post
Give I am a registered User
And I have signed in
When I go to Create Post Page
And Create a Post and Publish it
Then I should see the Post in the Index Page

or a Detailed way

Scenario: Create a Post
Given I am a registered User with name "Arun", email "foo@bar.com" and password "foobar"
And I sign in as "foo@bar.com/foobar"
When I visit Create Post Page
And I fill up Title as "Foo Post"
And I fill up Content as "Bar Contents for Foo Post"
And I publish the Post
Then I should see message "Post was successfully created."
And I should see post in the index page

The RSpec Book touches on this topic. It calls the first approach Declarative Style and second one Imperative Style. The Book also advises to use the former way if the project is more like a single man show where developer dons analyst/tester/coder hats and go for 2nd approach if the project has a bigger team and a business analyst for writing scenarios.

But its really a touch and go topic and its really difficult to gauge to how much in depth we have to go. The declarative seems to be pretty concise with loaded step definitions, but the imperative style gives a fair idea of what it takes to accomplish something in the system. So if we have a little bit informed tech savvy customer, probably second approach may add lot of value and clear lot of confusion. The imperative style is kind of walking the customer through the UI flows of the system.

But the conundrum with imperative style is if we already have good RSpecs for the Views/Controllers our RSpecs may read a lot like the imperative scenario and may look redundant.

So I can do rspec spec --format doc to get detailed documentation of the flows like the Cucumber imperative style. But of course it may not be good idea to share RSpecs with a Business User.

As the RSpec book says perhaps we need to mix judiciously both and perhaps experience only will teach to balance that.

The trigger for me to write this post was I was trying to create Scenarios for a sample project I am doing and just one hour I spend switching a scenario between declarative and imperative and was pretty confused where I would/should settle.