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"

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"

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)

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


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 😉


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

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)
      it "should redirect to sign in page for get :index" do
        get :index
        response.should redirect_to(new_user_session_path)
      it "should redirect to sign in page for get :show" do
        get :show, :id => "123"
        response.should redirect_to(new_user_session_path)

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) }

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

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

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 =

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

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}')]")

describe "Footer" do
  extend LinkHelpers

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

   context "Admin" do
     before(:each) do
      @admin = Factory(:admin)
     it_behaves_like "a footer", admin_links

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:

   not signed in user
     behaves like a footer
       with About Us
       with Feedback
       with Disclaimer
     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'

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}')]")

describe "Footer" do
   extend LinkHelpers

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

   context "Admin" do
     before(:each) do
       @admin = Factory(:admin)
     it_has_a "footer", admin_links

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:

   not signed in user
     has a footer
       with About Us
       with Feedback
       with Disclaimer
     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!

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

class Post
has_and_belongs_to_many :users

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.password "foobar"
user.password_confirmation "foobar"
user.role "author"

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

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

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" : [
], "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 "" and password "foobar"
And I sign in as ""
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.

Phusion Passenger + Apache2 for RoR

Ok here goes my little notes on making a small nifty Rails App run on Apache2 with mod_rails provided by Phusion Passenger.

The installation of mod_rails is pretty straight forward. The installation steps are small and well documented here plus you have the amazing rails cast by Ryan Bates.

After watching the videos and reading the steps well I thought its gonna be a breeze I am going to wind up in 15mts and going to enjoy the night! Sigh! But things went wrong a 15mts exercise consumed close 4/5hrs of my time.

Ok here is where the fun is all about – I use RVM to maintain my installs. The first step in passenger installation is obviously to install the passenger gem. Now I felt it would be good to put the passenger in global gemset rather than any specific one and there by making it available to all. So I did

rvm use 1.9.2@global

gem install passenger


In my system after the above step it said some libraries were missing in the system (Ubunut Lucid Lynx), so I had to correct those by manually installing them with apt-get. After I got all the dependencies installed I again ran the passenger install and everything went fine.

At the end of the passenger-install step, it would spew a few lines of code which we need to put it on apache2.conf file. For me those lines looked like

LoadModule passenger_module /home/arun/.rvm/gems/ruby-1.9.2-p136@global/gems/passenger-3.0.5/ext/apache2/
PassengerRoot /home/arun/.rvm/gems/ruby-1.9.2-p136@global/gems/passenger-3.0.5
PassengerRuby /home/arun/.rvm/wrappers/ruby-1.9.2-p136@global/ruby

Now I added a Virtual Host to Apache to point to my sample Rails App by adding the following to the apache2.conf

<VirtualHost *:80>
DocumentRoot /media/harddisk/work/ror/depot/public
<Directory /media/harddisk/work/ror/depot/public>
Allow from all
Options -MultiViews

So that is it – restart the apache and hit in your browser you should see your rails app. But hey! wait won’t entering make the browser go and search the Internet rather than your local system. Well yes, so we have to make a small exception in the file /etc/hosts. In the file add a line

Ok all set! now again enter the URL to your browser biff! now got a new error

no such file to load -- bundler

The error was obvious it was not able to find the bundler. But from terminal I gave

gem list -d bundler

It was showing proper output, means bundler gem was there up and kicking. Mind you this command I was giving from the gemset which I was working on. Then I started googling this error and got many suggestions and tried one by one and spent nearly 3hrs and couldn’t make any break through. It was really frustrating.

Then finally help arrived from Hongli Lai of Phusion Team through the Phusion Passenger Google Group. She was pointing to me that ruby I am using for Phusion given in apache2.conf file was pointing to global gemset while bundler was installed in the other gemset. So I had replace the line in apache2.conf to pick up the ruby from the gemset which I was working on. So suppose foo is your gemset change PassengerRuby line in apache2.conf to

PassengerRuby /home/arun/.rvm/wrappers/ruby-1.9.2-p136@foo/ruby

Yes! This worked. Now if you are running a static site things would start working now. But my sample app had some tables so when I fired up app in browser it was complaining that tables were missing in the production.

So if you run into a similar situation just migrate the tables to production with rake.
rake db:migrate RAILS_ENV="production"

In my case I had some load scripts as well which was for loading some sample data to tables, for loading those data into production use the rails runner with following option

rails runner -e production script/load_xxxxx.rb

That is it, now I see my rails app working well in my Apache2 server with mod rails.

Ok! here is a small tip, in order to restart the Rails App after changes you need not restart the server, you can give this command from Rails Application Root

touch tmp/restart.txt

Passenger would see the timestamp of restart.txt and reload the Rails App if needed.