# Practical Cucumber with Ruby Friends

## BDD with latest open-source tools

### Shashikant Jagtap

Copyright © Shashikant Jagtap 2015

## About this Book

### About

Thanks for downloading the e-book. This book is aimed for Developers and Testers who wish to learn about BDD and Cucumber with Ruby libraries. This book doesn't cover basics of Cucumber, please read 'The Cucumber Book' to know the basics about Cucumber.  This book is created by using Anthalogize which created books from WordPress site. You can find this content online at my personal website

Website

http://shashikantjagtap.net

Youtube Channel mentioned in the book:

https://www.youtube.com/user/BehatPHP

# Why Should You Read This Book

The agile development methodologies like Behaviour Driven Development becoming so popular and role of test engineer changing dramatically as teams started using Cucumber as BDD tool.

This book will give practical information about Cucumber and related open-source tools. It's essential for team to learn Cucumber and it's basic setup. Reading this book, you will able to

  * Setup Ruby-Cucumber Framework
  * You will learn Living Documentation
  * Learn about latest open-source tools and use it with Cucumber like Capybara, Appium, Poltergeist, Relish, Cuke_Sniffer etc
  * Setup Cucumber on Continuous Integration server like Jenkins, Hudson and TravisCI
  * Setup Cucumber for Mobile Test Automation.
  * Stay updated with the latest trends in BDD and Cucumber

# Thank You, London

I would like to say big thanks to City of London where I have learned everything I wrote here in this  book.

Contact Me :

Twitter : @Shashikant

Website : http://shashikantjagtap.net

## acknowledgement

## **I would like to thank.....**

All my friends who helped me to gain this knowledge in the field of BDD and Cucumber. I would also like to thanks meetup groups around London who spread useful information. Finally I would like to thanks City of London where I learned everything I wrote here

## **This Book is dedicated to ....**

My little son, Ipsit

# BDD and Gherkin Overview

## BDD Overview

**Abstract**

Behavior Driven Developement (BDD) is 'outside-in' software development methodology which changed tester's role dramatically in recent days. It's worth mentioning that BDD has created job insecurity for passive and non-creative testers. It doesn't mean that QA testing is tottaly replaced in BDD but it changed approach of testing dramatically. In this short article let's find out what and how can QA guy bring quality and business values in BDD projects.

**Few words about BDD**

Just in case you are new to BDD, It's term coined by Dan North in order to overcome pitfalls in Test Driven Development and bridging the communication gap between business and technology. In a summary, it works like this

  * Capture behaviour of system in the form of 'features' before writting code [Specification By Examples]
  * Think all possible scenarios in order to cover functionality and prevent bugs.
  * Implement behaviour in the form of 'step definitions'.
  * Verify that the implementation of the behavior makes the tests succeed.

Developers writes step definition in oder to implement system's behaviour. Once steps implemented, test automation is achived as a bonus. Developers covers almost everything in BDD then burning question arises 'Why we testers in BDD project?'

**What team can achieve with BDD**

  * Bridges communication gap between Business and Technology
  * Early feedback & clear communication
  * Business and Technology speaks same language
  * Business people start engaging in technology.

Here are some tips for Tester's to make BDD efficient and effective,

**Do's**

  * **Pull your Socks up to work in BDD**

As a QA, It's very important to understand basic concepts of the Behavior Driven Developement. The QA process is so different than SCRUM or any other methodologies. BDD is 'Out-side In' development methodology, so all the evil thinking that we used to use in order to find defects has to be used before writting code. This will help to prevent bug rather than finding bugs. Identificcation of all possible scenario will not allow bugs to enter into system.

In BDD, "Bug is a missing scenario". In case, if you find something not working after implemetation means you haven't identified that scenario before implemention. As a QA, you should act like 'quality police' throughout the project. Your role should be to prevent defect in early stage of implemetation. There is no official documentation mentioning QA role in BDD so be proactive to get all possible information from any source on internet, book, forums or meeting BDD practitioners.

  * **Get Involved Early**

It's very important to get involved in early stage of the project. It will help you to know in and out of the requrement and design scenarios. It is also important know scope of the project and design sensible senarios. Mostly projects manages made mistake, not to involve QA in early meetings of the project and QA guys always lag behind and it's major cause of many project didn't work out well in BDD. All the team should realise that QA plays major role in driving BDD project. As a QA, you should think all possible scenarios regardless if they are making sense. Every scenario you think is prevents bug in the system. Remember, if you miss any scenario this will turn as a defect in the implemented system.

  * **Be knowlageble**

Being knowledgable is nothing but gathering all the business requrements and thinking all possibilities around it and get it confirmed by product owner. Once you have complete understanding of the system then you know what's developers are going to implement. In a team, you should be more knowledgeable person within team so that you should know if developers are doing wrong. In most of the team, developers interacts more with product owner and tester didn't know more about system. In this case, tester has to rely on what developers are saying. It is very important that you should know in and out of the system even more than developer to make BDD project success. Developers should approach you in case they struggle to implement any scenarios.

  * **Lead Specification Workshop**

Specification workshop is opportunity for testers to be proactive to ask questions in order to get clear requiremnts from your product owner and discuss all possible scenarios with product owner. You should play key role in this meeting. If you fail to understand systems behaviour in this meeting then more chances are you will lag behind. Ideally, you should ask business owner sensible list of questions which in turn become acceptance tests. Here you can use your evil tedency to break the software before implementation. We are used to break software after implementaion and used to apply every possible techniques to break the software. It would be hard but you need to apply those techniques before implementions so the we can prevent bugs to enter into the system. In specification workshop, you shouldn't use 'GivenWhenThen' language. It's next step to write Gherkin for given system. In specification, you just need to mak sure you have communicated and discussed all possible scenarios of the desired system. At this stage you should have understood and identified all the acceptance tests of the system.

  * **Write Better Feature file**

Once you have all nesesary comminication with business, next step is to write feature files. Ideally, QA should take lead to write down all scenarios, preconditions, expected results in the form of feature files. Business analyst, scrum master can contribute to feature files to make it effective. Once team agree that we have covered every possible scenarios then developers can kick start implemetation.

**Few tips to write better feature file**

  1. Use & Refactor Background

Gherkin is a Domain Specific Language used to describe features in the 'GivenWhenThen' format. Gherkin has some cool features in order to avoid dupliction, repitative steps. Gherkin helps  readability for business users. Proper use of ' **Background** ' feature of Gherkin make much difference to avoid repitative task in each scenario. It is not mandotory to use background in each and every feature but it makes feature file readbale. There are few things you need to keep in mind while using 'background'. You have to keep your background section very short as user need to remember when they look into the scenarios. You shouldn't include technical stuff like starting some services, clearing cache, launching browsers in the background as most of the reader assume this things. You have to implemnet in the step definition by using proper hooks.

  1. Use of Data Tables, Examples, Doc String, Multiple table of example & nested steps

Gherkin provides ability to enhance your feature files by using tables. You can use ' **Data Tables** '. Data tables allow you to setup certain set of data as a pre-condition for the tests (Given) or as an examples in assertions (Then).  You need to use ' **Senario Outline** ' to extend  feature files by examples. **Doc String** is another cool feature of Gherkin which allows you to hardcode 'text' into your feature files eg. you can write email message in the quotes as an assertion. Gherkin also allow you specify multiple tables of example. Nesting Steps means hiding the implemention details. It can be biased as you can hide tecnical details but not the business details.

  1. Use tags and Subfolders to organise features

**Tagging** the features/scenarios with certain tags helps in catogorising them into different groups. You can apply filter to run the features/scenarios with specific tags. You can also create **subfolders** according to the functionality to organise features effectively.

Here is an example feature file which covers almost all the above mentioned points:

    feature: Login

    In order to secure my website
    As a business owner
    I want to implement login functionality

    Background: Given I am on login page

    @wip @smoke @browser @ci
    Scenario Outline: Check user's login credentials

    Given I filled <username> <email> and <passowrd>
    When I clicked on Login
    Then I should see <success or failure> message
    And I should get an email saying:
    """
    Dear User,
    You have just tried to login to our system. If your login is successful then you will get another email to verify you details.
    Thanks
    """

    Examples: Valid login

    |username|email         |password |success or failure|
    |Andy    |andy@gmail.com|abcd1234 |success           |
    |Mike    |mike@gmail.com|abcd1234 |success           |

    Examples: InValid login

    |username|email         |password|success or failure|
    |Andy    |andy@gmail.com|        |failure           |

  * **Watch developers & understand codebase**

Remember, you haven't done after you wrote solid feature files. Once you finished with feature files next step is to keep watch on how these features are being implemented by developement team without disturbing them. It would be always good to see how programmers oganise code and refactor code for later use. You should try to implement some features/scenarios by your own by refering the step definitions written by developers. This appraoch will speed up the implentation process. You should be fully aware of the test code as you will be the owner of the test code. You should know how to fix those tests in case they got broken in future.

  * **Balance tester-developer collaboration time.**

Collaborative working is always better in agile team but we need balance the time we are spending with developers and business value we are getting from collaboration. We shouldn't slow down developers by spending hours and hours by getting explained code base. This will definately slow down developers normal task on their plate. Always come up with list of questions/concern and ask for sutaible time to developers to discuss those questions. This time should be covered in the estimation to keep track of project estimation.

  * **Balance Service level tests and interface tests**

There should be proper balance between API level tests and interface tests. Service level tests are fast and stable while interface tests are brittle, slow and easy to break. You need to analyse business value of feature which needs to be run in real browser. You also need to select proper libraries and tools in order to run interface tests.

  * **Debug the tests**

In case, you get enough time during the feature implement, don't forget to debug the  implemented steps  by devlopers by providing different data or verfying negative test scenario. This will help if tests are not giving false positives.

  * **Drive the Continuous Integration**

Continuous Integration is key for successful agile projects. As a QA, you should drive the continuous integration. Keep a keen watch on the builds. Get the builld always green before deployment. visible continuous integraion makes a lot of diffrent in achieving quality.

**Don'ts**

In BDD, there are few things, you shouldn't do or shouldn't allow team to do. Success of the BDD projects depends on proper collection and execution of the business requirements. Below are rhe some of the points, you should keep in mind and avoid as much as possible.

  * **Allow developers to change feature files**

It may happen that developers wish to change the feature files as per their need so that implementation become easier for them. It can happen in situation where feature that team agreed is too complex to implement or developer feels that change in the feature file can make code more robust and re-usable. Whaterver the case, you shouldn't change the feature files unless agreed by team and business people. Change in feature files means indirectly change in the requirements. As a technology team we shouldn't change requirements unless agreed by business.

  * **Slow down Developers**

BDD projects are very volatile in nature and everybody in the team has tight schedule interms of the task assigned to them. Developers always complain that testers are passive and  non-technical so that they have spend more time with them in setting up local envirnment for them. It is quite natural that testers are not so technical kids so they always need some help from developers in setting up the enviroments, setting up the projects on local machine. As a a QA, you should be technical enough to set it by your own, if you are having some issues then you can call them for help but don't get your all job done by developers. This will definately affect the productivity of the development team.

  * **Allow dev to code the bug**

When someone find the bug in the prodution, they always complain that how did QA team miss that bug. It also need to take into considerartion that how did our programmer code the bug. The key idea of the BDD is to avoid the bugs than finding the bugs. The question here is how do you stop developers from coding bugs. Here are some symptoms that you can see when developers are about to code the bugs

  1.   Test the festures as implemented. Testing features one by one can help to verify that implementation is well
  2.   Make sure developer understand the functionality properly by looking into the code.
  3.   Keep keen watch on CI if developers checkins are breaking any tests.

  * **Miss any scenario, that would be a bug**

Good understandingof the concept and critical thinking about the possibilities can help to design all possible scenarios for perticular functionality. Remenber, if you miss scenario means you have addded defect into the system. It would be good practice to involve everybody from team in scenario design process.

**Beware of BDD Smells  
**

  * BDD lovers Vs BDD haters

In the team, there might me two groups of the people, on who like to implement BDD and another who hates BDD. Getting all the team member into BDD is the challenge. It would be a great idea to motivate all the people to involve in the process.

  * Flacky, Brittle & Slow Tests

One of the key concept around BDD is to keep business and technology engaged. Flacky tests means tests failing randomly without proper reason. Test failure is shaky so business and non-technical people starts loosing interest in the tests and features. Brittle tests means incidental and descriptive features which are so boring to read. Business people hates reading scenarios with steps giving lot of information about the system. Brittle features has lots of "AND" into it. No

  * Lack of Collaboration & Collaborative tools
  * Clients not reading Feature Files
  * Updating & Thrashing Scenarios

**Final thoughts**

Working with 'out-side in' software development methodologies like BDD are always challenging for testers. Use of communication skills and proper understanding of the process and role will help in delivering quality products.

###

##  BDD, Feature File & Gherkin Syntax

Behaviour Driven Development a.k.a BDD enforces agile team to write human readable, executable specification. Gherkin is a very nice Domain specific Language which support human readable syntax in different languages. BDD is all about bridging communication gap so writing better feature file is a key to success in the BDD projects.

Once you have all necessary communication with business, next step is to write feature files. Ideally, QA should take lead to write down all scenarios, preconditions and expected results in the form of feature files. Business analysts / product owners or even scrum masters can contribute to feature files. Once the team agrees all possible scenarios have been covered, then developers can kick start implementation.

Few tips to write better feature files

###  1. _**Use Background**_

Gherkin is a Domain Specific Language used to describe features in the 'GivenWhenThen' format. Gherkin has some cool features in order to avoid duplication or repetitive steps. Gherkin helps readability for business users. Proper use of the 'background' feature of Gherkin can help to avoid repetitive tasks in each scenario. It is not mandatory to use 'background' in each and every feature, but it makes the feature file more readable. There are few things you need to keep in mind while using 'background'. You have to keep your background section very short, just enough to keep the scenario in context. You shouldn't include technical stuff like starting some services, clearing cache, launching browsers in the background, as the reader will assume these things. You'll implement this in the step definitions by using proper hooks.

### _**2.Use of Data Tables, Examples, Doc String, Multiple tables of example & nested steps**_

Gherkin provides ability to enhance your feature files by using tables. You can use 'Data Tables'. Data tables allow you to set-up certain set of data as a pre-condition for the tests (Given) or as an example in assertions (Then).  You need to use 'Scenario Outline' to extend feature files by examples.  Doc String is another cool feature of Gherkin which allows you to hard-code 'text' into your feature files e.g. you can write email message in the quotes as an assertion. Gherkin also allows you to specify multiple tables of examples. Nesting Steps means hiding the implementation details.

### _**3.Use tags and Sub-folders to organise features**_

Tagging the features/scenarios with certain tags helps categorise them into different groups. You can apply a filter to run the features/scenarios with specific tags. You can also create sub-folders according to the functionality to organise features effectively.

Here is an example feature file covering almost all the above mentioned points:

    Feature: Login
    In order to secure my website
    ,
    as a business owner
    ,
    I want to implement login functionality

    Background: Given I am on login page

    @wip @smoke @browser @ci

    Scenario Outline: Check user's login credentials
    Given I filled <username> <email> and <password>

    When I clicked on Login

    Then I should see <success or failure> message
     a
    And I should get an email saying:
    "Dear User,
    You have just tried to login to our system. If your login is successful then you will get another email to verify you details. 
    Thanks
    "

    Examples: Valid login
    |username    |email          |password |success or failure |

    |Andy        |andy@gmail.com |abcd1234 |success            |

    |Mike        |mike@gmail.com |abcd1234 |success            |

    Examples: InValid login
    |username    |email          |password         |success or failure |

    |Andy        |andy@gmail.com|                  |failure            |

#### Conclusion

The key benefits of Behavior-Driven-Development (BDD) practices are communication enhancement and customer satisfaction which can be achieved by better communication & better feature files. Hope you find these feature writing tips useful.

Happy BDD !

# Setup development environment with Modern Toolkit

## Setup Local Web Development Environment on OSX Yosemite

### OSX Yosemite

Get fresh copy of the OSX Yosemite. I assume that you got nothing installed on your Mac and having clean hard drive. One good we can do at this point is create an Installation USB drive by running following command from terminal.

    $ sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction

You need at least 8GB of space. You can read this post on Mashable to do it step by step.

In this post, I will explain how to setup web development environment on OSX Yosemite. The tools include

  * Xcode + Command Line Tools
  * Git
  * HomeBrew
  * Cask for HomeBrew
  * Atom
  * RubyGems with RVM
  * NodeJS
  * Docker
  * Vagrant

Now Let's get started with that

### Xcode

Now that we got fresh version of OSX Yosmite installed. We can get Xcode from the Apple Store. Just sign in with your Apple ID and Download Xcode from the Apple Store. It will take some time and space to get it installed. It will be Xcode version 6.1.1 which is latest at the moment. Xcode will give you Git as a bonus.

Now in  order to install command line tools for the Xcode we need to run following command

    xcode-select --install

This will install command line tools for the Xcode. It will take 4-5 minutes.

###  Git Setup

Now that, we have Xcode installed which gives Git as a bonus. Now we have Git installed with Xcode. Let's setup our existing GitHub account. We can run following commands with your GitHub details

    git config --global color.ui true
    git config --global user.name "YOUR NAME"
    git config --global user.email "YOUR@EMAIL.com"
    ssh-keygen -t rsa -C "YOUR@EMAIL.com"

Now it will generate SSH key in the '~/.ssh/id_rsa.pub'. We need to add it into GitHub. Now try to ssh in to git.

    ssh -T git@github.com

You will message that you are successfully authenticated.

You can get GitHub for Mac which looks cool.

###  HomeBrew

HomeBrew is awesome package management for Mac OSX. We can install other packages with HomeBrew

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

HomeBrew Install :

**Install Cask  **

Cask will install Mac Application in the single command.

    brew install caskroom/cask/brew-cask

This will look like :

Now we will install following app with Cask.

  * iTerm
  * Atom Editor
  * Google Chrome
  * Vagrant   Need [VirtualBox to be installed ]
  * Vagrant-manager

    brew cask install atom
    brew cask install google-chrome
    brew cask install iterm2
    brew cask install parallels
    brew cask install vagrant
    brew cask install vagrant-manager

Vagrant installation looks like this:

Now we will install following packages with Brew

  * NodeJS

  * Docker

  * PhantomJS

PhantomJS is a headless browser. We can install it using

    brew install phantomjs

### RVM

RVM is ruby version manager. We can install it

    $ \curl -sSL https://get.rvm.io | bash -s stable

RVM Install

There are many packages and Apps we can install with HomeBrew and Cask.

## Top 10 Toolkits for the Modern Web Developer

### Modern Web Development

Web development is changing drastically with as open-source community is growing fast and lots and lots new tools coming into the market. Gone are the days where developers are just developing apps using old school techniques. Software development methodologies like BDD, TDD are growing rapidly which in turn changing the role of the web developer.

In this post, we will introduce some modern tools which every web developer should show.

### Modern Toolkit

The tools varies depending on the which technology you use but there are some general toolkit which can be useful and handy for the web development.

### Dependency and Package Management Tools

Package management is a collection of the software packages which ease the process of installing, upgrading, deleting and configuring software packages from the project or computer operating system. As most of the web developers use Linux or Mac OSX for the web development, we had plenty of options

**Homebrew**  is a package manage for OSX. Homebrew can be easily installed with Ruby with the following command.

    $ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Once installed, We can then install packages with simple command

    $ brew install {package_name}

Packages installed with Homebrew are installed at  **"/usr/local/Cellar"**  directory in OSX. There are various options available for uninstall, list, search, update or upgrade brew packages. Usage and troubleshooting information just do

    $ brew help

**MacPorts **is another package manager for the OSX. In order to install MacPorts, we need to have Xcode with command line tools. We can install  depending on OSX version. Once installed, you can install packages

    $ port install {package_name}

** **

Packages installed via MacPorts are installed in the "/opt/local" directory in the OSX. Similar to Homebrew, we can uninstall, search, list, update packages. Look at Quick Start Guide

**RPM**

RMP a.k.a Red Hat Package manager  is a package management system intended for the Linux Distribution. We can install repositories over internet using RPM front end like YUM, APT etc.

APT a.k.a Advance Packaging tool  is package management system for the Debian GNU/ Linux distribution. APT packages can be installed using

    $ sudo apt-get install {package_name}

Installed packages can be removed, upgraded or listed. Read ubuntu AptGet guide.

** **

YUM is package manager used to install, update, uninstall the rpm packages.

    $ yum install {package_name}

NPM a.k.a node package manager is a package manager which install, manage and publish packages for the Node.js. NPM is written entirely in the JavaScript. NPM allows user to install application available in the Node registry.

You can install node packages globally with following command

    $ npm install -g {package_name}

Node packages can also be installed locally like this :

    $ npm install {package_name}

This will create a 'node_modules' directory inside the project and install the package inside it. You can then execute the package using:

    $ ./node_modules/.bin/ {package_mane}

The NodeJS dependencies can managed by the 'package.json' file. We can define all the all the dependencies in the one file and install at the same time. You can validate 'package.son' file by using 'package-son-validator'. Example 'package.json' looks like this:

    {
      "name": "Packages",
      "version": "0.0.0",
      "description": "nodeJS modules",
      "dependencies": {
        "webdriverjs" : "*",
        "appium": "*"
      },

      "author": "Firstname Lastname",
      "license": "MIT"
    }

Now, we need to run 'npm install' to install listed packages.

Bower is a package management system can be installed with NodeJS. Bower allows us to install third party libraries, frameworks and utilities. Bower can be installed like:

    $ npm install -g bower

Now that, we have installed 'bower' so we can install bower packages like:

    $ bower install {package_name}

The packages installed can be found in the 'bower_components' directory. You can search for the bower packages. Similar to the  'package.son' for the NPM, Bower has 'bower.json' file to define all the dependencies for the project.

RubyGems

RubyGems is a package manage for the Ruby programming language. RubyGems are often called as 'gem'. We can install Gems like this:

    $ gem install {gem_name}

Bundler is a great way to manage Gems in the Ruby projects. RubyGems has 'Gemfile' to define all the required dependencies for the project. The bundler will install all the dependencies in the 'vendor/' directory.

    $ bundle install

## Modern Web Development and Dependency Management

### Package Management

Package management is a collection of the software packages which ease the process of installing, upgrading, deleting and configuring software packages from the project or computer operating system. As most of the web developers use Linux or Mac OSX for the web development, we have plenty of options

### HomeBrew

**Homebrew**  is a package manage for OSX. Homebrew can be easily installed with Ruby with the following command.

    $ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Once installed, We can then install packages with simple command

    $ brew install {package_name}

Packages installed with Homebrew are installed at **"/usr/local/Cellar"** directory in OSX. There are various options available for uninstall, list, search, update or upgrade brew packages. Usage and troubleshooting information just do

    $ brew help

### MacPorts

**MacPorts** is another package manager for the OSX. In order to install MacPorts, we need to have Xcode with command line tools. We can install  depending on OSX version. Once installed, you can install packages

    $ port install {package_name}

Packages installed via MacPorts are installed in the "/opt/local" directory in the OSX. Similar to Homebrew, we can uninstall, search, list, update packages. Look at Quick Start Guide

**Apple Store**

Apple Store  is another place to find a software packages required for the web development. We can search and install packages from the Apple store. We need to have an Apple ID

**RPM**  
RMP a.k.a Red Hat Package manager is a package management system intended for the Linux Distribution. We can install repositories over internet using RPM front end like YUM, APT etc.

APT a.k.a Advance Packaging tool  is package management system for the Debian GNU/ Linux distribution. APT packages can be installed using

    $ sudo apt-get install {package_name}

Installed packages can be removed, upgraded or listed. Read ubuntu AptGet guide

YUM is package manager used to install, update, uninstall the rpm packages.

    $ yum install {package_name}

## Application level package management tools

### NPM

 NPM is a node package manager.You can browser any package by searching on the npm website. You need to install NodeJS in order to use NPM. NodeJS can be installed on any platform.

Once you installed NodeJS. Any package can be installed using

     $ npm install

Another approach to NPM packages are create a 'package.json' file and mention all the dependencies. You can read more about package json file here . Example package.json file looks like this

    {
      "version": "0.0.0",
      "description": "My Package",
      "dependencies": {
        "webdriverjs" : "*",
        "appium": "*"
      },

      "author": "Shashikant Jagtap",
      "license": "MIT"
    }

Now that, we have all our dependencies in the package.json file. We can run 'npm install' which install all the dependencies in the directory ' **./node_modules** ' . Now We can run installed package e.g Appium like this

    $ ./node_modules/.bin/appium

### RubyGems

Rubygems is a package management framework for the Ruby packages. You can latest download latest version of the RubyGems from the download page. Once you installed RubyGems, you can install any Gem with the command

    $ gem install {package_name}

Another approach to install Gems are from 'Gemfile' with Bundler which manage versions of the RubyGems installed. We can create a 'Gemfile' and list all the dependencies over there. Typical gemfile looks like this:

    source "http://rubygems.org"
    gem 'cucumber'
    gem 'capybara'
    gem 'bddfire'
    gem 'selenium-webdriver'

Now that, we have all the Gems in the Gemfile, now we can install all these gems with bubdler like this

    $ bundle install

All the Gems will be installed in the './vendor' directory.

### Composer

Composer is a package management system for the PHP packages. We can install composer by running one simple command

    curl -sS https://getcomposer.org/installer | php

It will download 'composer.phar',  We can make it global by copying composer.phar into local binary.

    $ mv composer.phar /usr/local/bin/composer

 We can create 'composer.json' file with all the required dependencies. Composer.json file looks like this:

    {
        "require": {
            "behat/mink-selenium-driver": "*"

        },
        "minimum-stability": "dev",
        "config": {
            "bin-dir": "bin/"
        }
    }

Now we can install these package by running command

    $ composer install

These packages will be installed and can be run from the 'bin' directory.

    $ ./bin/{package_name}

### Bower

Bower is a package management system for the web. It's based on the NodeJS and npm. Bower can be installed with the npm

    $ npm install -g bower

This will install bower globally.

Bower will create 'bower.json' file with template with 'bower init' command and we can add our dependencies. You can also search for the bower packages . Typical bower.json looks like this:

    {
      "name": "my-project",
      "version": "1.0.0",
      "ignore": [
        ".jshintrc",
        "**/*.txt"
      ],
      "dependencies": {
        "<name>": "<version>"
      }
    }

Now that, we have all bower dependencoes in the bower.json file. We can now install those dependencies

    $ bower install

Now, we can make use of the bower dependencies.

#### Conclusion

Package and dependency management system makes web development smarter and faster. Modern web development practices uses dependency management to separate dependency code form the application code.

## Speed up your BDD with Sublime Text 2

As far as I remember, We had London Behat User's meetup at SkillsMatter, London on 23, May 2012 titled "Speed up your BDD with Sublime Text 2"

Christophe Willemsen [@ikwattro] came to London all the way from Belgium to present Behat/Mink Snippets he worked on. Here is  Github repository.  Now these snippets are part of Package Controller of the Sublime Text 2. I would like to thank him for his awesome work. In this short tutorial, I will try to explain his work on Behat snippets for Sublime Text 2 and use of Gherkin syntax.

### BDD & Feature Files

The key benefit of the Behavior Driven Development BDD] is to bridge communication gap by writing human readable specifications. In the language of BDD, these specifications are often written in Domain Specific languages like [Gherkin. Well written feature files are the building blocks of the BDD project.

Here are some common problems usually faced by teams [Developers, QA, Business]  in writing feature files:

  * Not familiar with Gherkin syntax.
  * Don't know how to use 'Example Tables' in the scenarios.
  * Don't know how & when to use "Given, When, Then, And, But" statements. [Mixing of GWT]
  * Don't know how to write reusable steps using Gherkin.

This problems can be avoided by using perfect text editor like "Sublime Text 2"

### Sublime Text 2

Sublime text is a perfect editor for writing feature files in the BDD projects, having said that I have tried couple of editors and compared to them Sublime Text 2 worked way better.

I have used NetBeans for long time, It was working well with Cucumber plugin as it can format your feature files easily, create template feature files, Gherkin syntax highlighting, error reporting in case of wrong Gherkin syntax etc etc. Looks Good. There are couple of thing which annoyed me a lot about NetBeans. NetBeans Cucumber plugin crashes whenever it wish to and once it crashed you have to restart NetBeans which is too slow to kick off.

I also tried 'VIM' also spend enough time to learn about Vim and it's plugins. Thanks God, I have came across this blog post just in time without spending more time to lean Vim rather than learning actual implementation techniques. Can't argue that 'Vim' is awesome editor for Geeks but to me 'Learning Tools & Technologies' is more important than 'Learning Editor' at this point.

So, Sublime Text 2 is my best friend!!. You can download it from website . You can read awesomeness of Sublime Text 2 in the blog post 'Tricks and Tips" by Net tuts+. Things I like about Sublime Text 2 are

  * Works On Mac OSX and Linux.
  * Lighting Fast while Editing and Switching Files from Command Palette.
  * Package Control which supports loads of plugins with easy installations. Thanks to Will Bond
  * How Can I forget 'Multiple Cursors' while editing ?
  * Supports 'n' number of  Languages.

Ok. enough description here. I would strongly recommend this Video in order to learn awesomenimity  of Sublime Text 2 and how it stand out from other editors.

## Sublime Text with BDD Tools: Behat and Cucumber

I assume that you have installed Sublime Text 2 and downloaded Package Control plugin which is fairly easy and straightforward.

How to install Packages from Package Control. ?

  * Type 'Command+Shift+P' 
  * Start typing "package" in the command palette and it will show different options.
  * Select Install Packages & hit Enter

Now, Install following Packages to get started.

  *  Behat
  * Sublime-Behat-Snippet
  * Cucumber
  * Gherkin[Cucumber] Formatter

### Start Writing Feature Files

Believe it or not you can write sample feature file within a minute. You may probably argue that NetBeans Cucumber plugin provide template feature file much easier but real power of sublime Text is it's speed. Follow 3 steps and you will get Feature files within a minute.

1] Hit 'Command + Shift + P' & type ' _Gherkin_ '. Hit Enter. It will set syntax to "Gherkin"  
2] Hit 'Command + Shift + P' & type ' _feature_ '. Hit Enter. This will create story format  
3] Hit 'Command + Shift + P' & type ' _scenario_ ' Or 'Scenario Outline' && Hit Enter. This will create Scenario  
_4] Hit 'Command + Shift + P' &_ type ' _example_ ' && Hit Enter. This will create example table.

You will see feature file created like this:

### InBuilt Mink API's

If your are using Behat-Mink for UI automation then Sublime Text has huge benefit for you. You can access built in Mink API's directly from the Sublime. List of Mink API's can be found here . You can also refer behat-cheat-sheet to get help.

### Bhehat-Mink : Given

You can type ' _given_ ' in the command palette [ Command +Shift + P] and you will list of available options like this.

### Behat-Mink: When

You can type ' _when_ ' in the command palette [ Command +Shift + P] and you will list of available options like this.

### Behat-Mink: Then

You can type ' _Then_ ' in the command palette [ Command +Shift + P] and you will list of available options like this.

#### Video Demo

Let's Create Sample Feature File using Sublime Text. Watch this Video.

#### Conclusion

Writing BDD feature files become so easy by using Sublime Text and it's packages like 'Gherkin', 'Cucumber' and 'Behat'. You can write better feature files using full power of Sublime Text2 .

**Happy BDD !!  ** _ _ __

## Setting up VM's with Vagrant on OSX Mavericks

### Vagrant

Vagrant is a awesome tool to setup repeatable development environments. Vagrant helps developers by introducing common configuration and building development environments across Mac OSX, Linux and Windows.

### Requirements

To use vagrant on Mac OSX Mavericks, we need following

  * VirtualBox

Download VirtualBox for Mac OSX and install it by following instructions.

You will see something like this. You have now got VirtualBox on your Mac

  * Vagrant for OSX

Previously vagrant used to come up with RubyGems. You would have to just do

    $ gem install vagrant

This method is no longer supported now, so if you have installed vagrant using RubyGems un-install it using

    $ gem uninstall vagrant

Now, Download vagrant.dmg file for Mac from official vagrant website

Complete the installation by following instructions, you will see something like this

Now you have vagrant installed.

### Boot VM's with Vagrant

Now that, we have installed vagrant on our Mac. You can open i-Term Or Terminal and type

    $ vagrant -v

This should print version of the vagrant installed. You can now see what are the command line options are available for vagrant

    $ vagrant help

My i-Term looks like this :

### Add Vagrant Box CentOS

There are number of vagrant boxes available on vagrantboxes website. We will now use "CentOS 6.3 x86_64 minimal" box

Let's now add this box and name it 'CentOS'

    $ vagrant box add CentOS https://dl.dropbox.com/u/7225008/Vagrant/CentOS-6.3-x86_64-minimal.box

    $ vagrant init CentOS

This will create a "Vagrantfile" in your directory which we can modify accordingly

My i-Term window look like this:

### Vagrant UP

Now that, we got CentOS VM ready to boot. We can boot this VM by using 'vagrant up', this will run CentOS  machine in the VirtualBox.

    $ vagrant up

This will take few minutes, be patient.

### Vagrant SSH

Now we have CentOS VM running in the virtualBox. We can 'ssh' into that VM and do crazy things. Now let's ssh into machine and check if correct version of CentOS installed.

    $ vagrant ssh

Look at these commands

Once you done all work on this VM you can halt this VM

    $ vagrant halt

This will halt VM. There are plenty of command line options we can play with.

#### Conclusion

We can spin up multiple VM's using vagrant and keeping development environment config very simple. Use Vagrant and have fun !

## Installing and Setting up Github's Atom Editor on Mac OSX Mavericks

### Atom Editor

GitHub has just released beta version of 21st century hackable editor for developers called 'Atom'. Currently, Atom (@AtomEditor) is in beta status and will be available only via invite. You can request an invite from GitHub by sending your details and you will get an invite soon Or you can ask your friends, colleagues to send you invite.

Once you got an invite, you need to follow a link from your email which will allow you to download Atom for your Mac. Currently Atom is only available for Mac **OSX version 10.8** and above.

###  Launch Atom

Once you download zip with Atom package, you need to  install it on your Mac OSX and open Atom Editor for first time. It will look like this:

###  Move Atom to /Applications

Copy Atom into your Applications directory so that you can launch it straight from your Spotlight or Alfred. It would be useful.

### Atom Command Line

Once you have installed Atom, you can use many command line options for Atom. You can install packages, themes from command line. You need to have installed node and npm. You can find help from your i-Term

    $ apm help install

This will give you information about usage of 'apm' command.  if you got an node error then you need to upgrade your node and npm version

    $ brew upgrade node
    $ npm update npm -g

Now you should be on the latest version of the node and npm:

 Now you shouldn't get any any error while accessing 'apm'

You can navigate to directory and launch atom from there by using atom command

    $ cd /path/to_project/
    $ atom

This is pretty awesome way to launch Atom for different project.

###  Install Themes and Packages

You can now install packages and themes available at the official packages website. You just need to find the name of the packages and install those packages from command line.

### Search Packages

You can search available packages from command line get list of packages available for that language or tool. Suppose, you want to search all packages available for Cucumber BDD tool. You can search that from your command line.

    $ apm search cucumber
    $ apm install cucumber

This will install Gherkin style syntax highlighting for your Cucumber feature files. You can explore packages for the languages and tools of your interest.

### Search Themes

You can also search themes and install directly with simple commands. I did search for themes for Mac and Twilight theme and installed

    $ apm search mac
    $ apm install atom-mac-theme

You can search and install packages from the command palette of the Atom (cmd+Shift+P) ans type install.

Well, you can configure your Atom editor by using configuration guide in the official documentation.

### Atom Vs Sublime Text

Being user of Sublime Text, I found it's pretty similar in terms of keyboard shortcuts and functionality. In the Atom introduction blog post , explained how Atom is different from Sublime Text and TextMate. Atom;s extensibility is the key. Atom will be easily plugged with the any language and tool. Hope fully it will be free, hope so !

## Setting up oh my Zsh with iTerm2 on MacBook

### Oh-My-Zsh

Whenever I am on My Mac, I always love my tools and editors stand out from traditional and old-fashioned tools. Being a software professional we use terminal a lot to execute some commands. In the past, I have used terminal for Mac, iTerm2 in my day to day job and at home. Today I fall in love with 'oh-my-zsh' with iTerm2 and it's simple awesome. in this post, I will show you how I set that up on my MacBook Pro with OSX Yosemite.

### Install oh-my-zsh

It's very simple, Open your bloody old style terminal Or iTerm 2 screen and type

    $ curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh

Now you have installed oh-myzsh. Worth confirming by typing 'zsh –version'

Now you should have '~/.zshrc' file created in your Home directory. We need to configure that to use oh-my-zsh.

### Install plugins

Now that, we have .zshrc file, You can browse through various plugins here. I use git, Ruby, Brew, Vagrant, NodeJS, npm, Rubygem, Bundler in my day to day job. So open up .zshrc file

    $ vim ~/.zshrc

Add following line

    plugins=(git git-flow atom bundler composer gem jira node npm rvm  rails textmate ruby cap brew github mysql osx vagrant)

### Install Themes

Now you have to select your favourite theme from the list of themes. I have selected 'dallas' theme as it has ruby version and git brand be default. Add this line to .zshrc

_**export ZSH_THEME="dallas"**_

Now you are all set. Now open up iTerm 2 again. Feel the magic, it's completely changed.

Mine looks like this :

It looks great, isn't it ?

#### Watch it on YouTube

Watch Youtube Here

# Cucumber and Friends

## Cucumber, BDD and 21st Century Hackable Atom Editor

GitHub has just launched Atom Editor, I am using it quite a lot and posted a blog on how to install and setup atom editor on Mac OSX. Since the Atom has grown rapidly and community is adding lots of packages to improve experience of Atom.

While working in the Behaviour Driven Development (BDD), we use various BDD tools like Cucumber (@cucumber_pro) and Behat (@BehatPHP) and we expect editor support to make our life easier. Sublime Text has been my favourite editor as of now as it supports BDD tools very well. Since Atom comes in place, it looks promising.

In this short tutorial, we will see

  * Decorating Atom Editor 
  * Installing Cucumber and BDD related packages(Cucumber, Ruby, Bundler, TravisCI, Rake)
  * Using Atom Packages in the Cucumber Project
  * Video Demo

### Decorating Atom

You can decorate Atom editor with UI Themes and Syntax Themes and have experimented many UI and Syntax themes and liked combination of UI theme 'Atom Dark' and Syntax theme 'Ninja-syntax". You can install them by following commands

    $ apm install atom-dark-ui
    $ apm install ninja-syntax

You can them configure these themes from the Atom settings by pressing "cmd + ," key from your Mac. Now My Atom is looking like this:

Now, you can setup your favourite font size and font-family from the Atom setting.

### Installing BDD related Packages

You need few basic set of packages from the existing packages available on Atom's website. Here we will see some useful packages

### Git Related Packages:

Here are some useful packages required to configure with GitHub. You can install these packages from the command line. Let's search all Git related packages and install them

    $ apm search git

This will give you list of packages related to git and you can pick some useful and install. I have installed following packages

    $ apm install git-diff
    $ apm install git-difftool
    $ apm install language-git
    $ apm install github-web

This will give us enough to config github with Atom Editor. There is nice blog post to see Git integration for the Atom.

### BDD Related Packages:

### Cucumber

There are some cucumber related packages available for cucumber

    $ apm search cucumber

I have installed cucumber, cucumber-runner, and cucumber steps packages.

There is some Gherkin related packages available for Atom for behat.

    $ apm install behat-atom

If you are using Capybara/Rspec you can use some snippets

    $ apm install capybara-snippets
    $ apm install rspec
    $ apm install rspec-snippets

### Ruby, Bundler and Travis Related

There some nice packages related to ruby, RubyGems, Bundler and TravisCI. You can install these packages

    $ apm install test-status
    $ apm install ruby-bundler
    $ apm install travis-ci-status

These packages will be enough to get started with Cucumber project.

### Using Packages in the Atom

Now that, we have all necessary packages installed for Aom. Let's see how to use them in our Cucumber Project. I have used Demo project "Cuke-Experiement" . Clone the project and launch atom

    $ git clone https://github.com/Shashikant86/Cuke_Experiment
    $ cd Cuke_Experiement
    $ atom

### Using Ruby-Bundler

We have installed Ruby-Bundler package for Atom.  Let's open 'Gemfile' in our project and in the fuzzy-finder (cmd+Shift+P) type "Bundler" we will see "Bundle Install" and Bundle List" commands.

Bundle Install will install bundler and 'Bundle List' will show all the RubyGems installed. You will watch it in the Video Demo below.

### Using Cucumber-Runner

Cucumber Runner is another important package which runs Cucumber in the Atom editor. You just need to open an 'feature' file you want to run. Right click will give you an options

**Run Feature File** : This will run an entire feature file with Cucumber.

**Run Cucumber at Line:  **This will run Cucumber for only that particular step.

### Using Test-Status

Test-Status is cool package which will scan 'Rakefile', 'Gruntfile in your project and run test. Rakefile will use 'rake test' and Gruntfile will use 'grunt test' . We need to add following snippet to our "./atom/config.cson" file

    'test-status':
      'Rakefile': 'rake test'
      'Gruntfile.*': 'grunt spec'
      'gulpfile': 'gulp test'

Now that, in our project we got an Rakefile, from fuzzy finder type "test status"  this will give an option to 'Test Status: Run Test'

This will run 'rake test' and log output. While tests are running, output status will turn orange and will turn back to Green or Red as per test status.

You can also track status of TravisCI build in the status bar. It's Green at the moment.

#### Video Demo

Watch Here

HAPPY BDD with GitHub's 21 Century Editor !!

## Ruby 2.0.0 on MacBook Pro.

### Ruby 2.0.0

Ruby has just announced new version recently Ruby 2.0.0-p0. I can't wait to install new version in my Mac. I already installed Ruby using RVM, but need to upgrde it to newer version, here is how I did that.

I taken reference from the awesome post , You must have Xcode installed with command line tools and HomeBrew.

Let's install RVM

    Shashi-MacBook-Pro:~ user$ curl -L get.rvm.io | bash
    source ~/.rvm/scripts/rvm

Edit yout .profile Or .bash_profile and Add following line.

    [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"

You need to resolve some conflicts using 'brew doctors'

### Install

Now, Run following commands to install Ruby 2.0.0

    rvm get head

    rvm requirements

    rvm install 2.0.0

You will see something like this in the terminal output

Once you done with installtion you may get this error ' rvm_codedesign_identity'

You can solve it by running command

    chmod -x $rvm_path/hooks/after_install_codesign

My Terminal looks like this after that.

Now, make it default and check vesion

    Shashi-MacBook-Pro:~ user$ rvm use 2.0.0
    Using /Users/user/.rvm/gems/ruby-2.0.0-p0
    Shashi-MacBook-Pro:~ user$ rvm default 2.0.0
    Shashi-MacBook-Pro:~ user$ ruby -v
    ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin11.4.2]
    Shashi-MacBook-Pro:~ user$ which ruby
    /Users/user/.rvm/rubies/ruby-2.0.0-p0/bin/ruby
    Shashi-MacBook-Pro:~ user$ curl -L get.rvm.io | bash

Enjoy Ruby 2.o.0 !!

## Mac OSX 10.8.2, Cucumber, nokogiri and xCode

### Nokogiri Gem

While using Cucumber, you may need to use nokogiri gem for various reasons. While using it on Mac OSX 10.8.2 you may see following error while 'bundle install' or "bundle update'

    Installing nokogiri (1.5.9) 
    Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

            /Users/user/.rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb 
    extconf.rb:88: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    checking for libxml/parser.h... *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of
    necessary libraries and/or headers.  Check the mkmf.log file for more
    details.  You may need configuration options.

    Provided configuration options:
            --with-opt-dir
            --with-opt-include
            --without-opt-include=${opt-dir}/include
            --with-opt-lib
            --without-opt-lib=${opt-dir}/lib
            --with-make-prog
            --without-make-prog
            --srcdir=.
            --curdir
            --ruby=/Users/user/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
            --with-zlib-dir
            --without-zlib-dir
            --with-zlib-include
            --without-zlib-include=${zlib-dir}/include
            --with-zlib-lib
            --without-zlib-lib=${zlib-dir}/lib
            --with-iconv-dir
            --without-iconv-dir
            --with-iconv-include
            --without-iconv-include=${iconv-dir}/include
            --with-iconv-lib
            --without-iconv-lib=${iconv-dir}/lib
            --with-xml2-dir
            --without-xml2-dir
            --with-xml2-include
            --without-xml2-include=${xml2-dir}/include
            --with-xml2-lib
            --without-xml2-lib=${xml2-dir}/lib
            --with-xslt-dir
            --without-xslt-dir
            --with-xslt-include
            --without-xslt-include=${xslt-dir}/include
            --with-xslt-lib
            --without-xslt-lib=${xslt-dir}/lib
            --with-libxslt-config
            --without-libxslt-config
            --with-pkg-config
            --without-pkg-config
            --with-libxml-2.0-config
            --without-libxml-2.0-config
            --with-libiconv-config
            --without-libiconv-config
    /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
    You have to install development tools first.
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:506:in `try_cpp'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:970:in `block in find_header'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:790:in `block in checking_for'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:284:in `block (2 levels) in postpone'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:254:in `open'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:284:in `block in postpone'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:254:in `open'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:280:in `postpone'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:789:in `checking_for'
            from /Users/user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:969:in `find_header'
            from extconf.rb:116:in `<main>'

    Gem files will remain installed in /Users/user/.rvm/gems/ruby-1.9.3-p194/gems/nokogiri-1.5.9 for inspection.
    Results logged to /Users/user/.rvm/gems/ruby-1.9.3-p194/gems/nokogiri-1.5.9/ext/nokogiri/gem_make.out

    An error occurred while installing nokogiri (1.5.9), and Bundler cannot
    continue.
    Make sure that `gem install nokogiri -v '1.5.9'` succeeds before bundling.

It looks like this in my terminal

Not sure what is the root cause of this error but this error appears randomly while doing 'bundle update'

### Solution

  * Quick and easy fix for this error is to create following sym-link

    sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2

  * Another solution is to check and install updates of xCode Ducumentation

This can be done by XCode-> Preferences-> Downloads->Documentation The screen will look like this

Now, install nokogiri gem

    $ gem install nokogiri

You will see that error has disappeared ! I got something like this

    Shashi-MacBook-Pro:cucumber user$ gem install nokogiri
    /Users/user/.rvm/rubies/ruby-1.9.3-p194/bin/gem:4: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    Building native extensions.  This could take a while...
    Successfully installed nokogiri-1.5.9
    1 gem installed
    Installing ri documentation for nokogiri-1.5.9...
    Installing RDoc documentation for nokogiri-1.5.9...

Now, Go and Enjoy Cucumber and BDD.

## Cucumber, Capybara and Poltergeist as Developer Tools: Network Traffic Capture

### BDD with Cucumber, Capybara and Poltergeist

Cucumber is a awesome BDD tool which can be used with different web acceptance testing frameworks and different drivers. We can use BDD combination of Cucumber + Capybara + Poltergeist to automate acceptance criteria. Read my previous blog here to know more about it.

In this tutorial, we will see how we can capture network traffic of webpage and use it to check that all resources loaded correctly. We will use Poltergeist as a Capybara driver network traffic of the webpage.

### Network Traffic Capture

Working as a developer it's quite important to use developer tools to see loaded resources on the webpage. We generally use developer tools embedded in the browser. e.g Firebug for Firefox, Developer tool for Safari and Chrome OR Charles.

We can see all the network traffic for BBC website like this :

This is a developer tools used with Safari 7.0.

### Poltergeist and Network traffic

Poltergeist is a headless driver for capybara which uses PhnatomJS to run scenarios without popping browser window. There is a GitHub repo 'Poltergeist-Demo' to see Poltergeist in an action. Poltergeist has a amazing method to inspect network traffic on the page

    page.driver.network_traffic

We can also reset and clear network traffic on any page by using mehtods

    page.driver.clear_network_traffic
    page.driver.reset

Let's see how to test all loaded resource on the web page using Cucumber+Capybara+Poltergeist

### Cucumber Project : Poltergeist-Network-Traffic

### Project Setup

Let's create new cucumber project for this demo. Open Terminal (i-Term)

    $ mkdir poltergeist-network-traffic
    $ cd poltergeist-network-traffic
    $ vim Gemfile

Add following Gem into your Gemfile

    source :rubygems
    gem "sinatra"
    gem "shotgun"
    gem 'json'
    gem "capybara"
    gem "cucumber"
    gem "rspec", :require => "spec"
    gem "parallel_tests", "~> 0.12"
    gem "poltergeist"
    gem "selenium-webdriver"
    gem "rest-client"
    gem "json_pure"
    gem 'nokogiri', '~> 1.6.0'

Now, we will create configuration to register Poltergeist driver. We need to create ' _features_ ' directory and ' _support_ ' subdirectory and add ' _env.rb_ ' file

    $ vim features/support/env.rb

Add following code into your config file

    require "Capybara"
    require "Capybara/cucumber"
    require "rspec"
    require 'capybara/poltergeist'

    Capybara.default_driver = :poltergeist
    Capybara.register_driver :poltergeist do |app|
        options = {
            :js_errors => true,
            :timeout => 120,
            :debug => false,
            :phantomjs_options => ['--load-images=no', '--disk-cache=false'],
            :inspector => true,
        }
        Capybara::Poltergeist::Driver.new(app, options)
    end

Now, we will create a simple feature file ' _features/home_page.feature_ '

    Feature: Network traffic with all resources with Poltergeist
      In order to expolre poltergeist functionality
      As a capybara and poltergeist user
      I want to see the if it can load all resources using

    Scenario: View home page and list all loaded resources
      Given I am on the BBC home page
      When I called network traffic using Poltergeist
      Then I should see list of all resources loaded after a web page document has started to load

Now that, we need step_definitions to implement the feature. Let's create another file with code for network traffic implementation in it. ' _features/step_definitions/step_definition.rb'_

    Given(/^I am on the BBC home page$/) do
      visit "http://www.bbc.co.uk/programmes/a-z"
    end

    When(/^I called network traffic using Poltergeist$/) do
    end

    Then(/^I should see list of all resources loaded after a web page document has started to load$/) do
      page.driver.network_traffic.each do |request|
      request.response_parts.uniq(&:url).each do |response|
        puts "\n Responce URL #{response.url}: \n Status #{response.status}"
      end
    end
    end

### Ruby version, OSX Mavericks and Poltergeist

We need to use ruby 1.9.3 for this tutorial, you can use RVM to toggle between different ruby versions. If you are using OSX Mavericks, there is a open issue which sends chatty PhantomJS output while running cucumber. We need to run 'cucumber' with some hack

    cucumber  2> >(grep -v CoreText 1>&2)

It looks like this in my iTerm

### Run Cuke

Now lets run cucumber and see the output with list of resources loaded on the page with response code for each.

    cucumber  2> >(grep -v CoreText 1>&2)

It will give you output like this:

    shashimacpro:poltergeist-network-traffic user$ cucumber  2> >(grep -v CoreText 1>&2)
    /Users/user/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.3.4/lib/bundler/runtime.rb:216: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    Feature: Network traffic with all resources with Poltergeist
      In order to expolre poltergeist functionality
      As a capybara and poltergeist user
      I want to see the if it can load all resources using

      Scenario: View home page and list all loaded resources                                         # features/home_page.feature:8
    2013-12-21 22:21:25.893 phantomjs[1429:507] Can't open input server /Library/InputManagers/Safari140
        Given I am on the BBC home page                                                              # features/step_definitions/step_definition.rb:1
        When I called network traffic using Poltergeist                                              # features/step_definitions/step_definition.rb:5
        Then I should see list of all resources loaded after a web page document has started to load # features/step_definitions/step_definition.rb:11

           Responce URL http://www.bbc.co.uk/programmes/a-z:
           Status 200

           Responce URL http://static.bbci.co.uk/frameworks/requirejs/0.13.1/sharedmodules/require.js:
           Status 200

           Responce URL http://static.bbci.co.uk/frameworks/barlesque/2.59.1/orb/4/style/orb.css:
           Status 200

           Responce URL http://static.bbci.co.uk/modules/plugin/favourite/1.1.15/1_1_15/style/favourite.min.css:
           Status 200

           Responce URL http://static.bbci.co.uk/modules/personalisation/0.8.2/style/dialog.css:
           Status 200

           Responce URL http://static.bbci.co.uk/frameworks/barlesque/2.59.1/orb/4/script/orb/api.min.js:
           Status 200

           Responce URL http://static.bbci.co.uk/gelstyles/0.5.0/style/core.css:
           Status 200

           Responce URL http://www.bbc.co.uk/modules/branding/css/0_9_0/programmes_default-1377003249.css:
           Status 200

           Responce URL http://static.bbci.co.uk/programmes/2.74.0/styles/global.css:
           Status 200

           Responce URL http://www.live.bbc.co.uk/frameworks/fig/1/fig.js:
           Status 200

           Responce URL http://static.bbci.co.uk/frameworks/barlesque/2.59.1/orb/4/script/vendor/edr.js:
           Status 200

           Responce URL http://tps.bbc.com/wwscripts/data:
           Status 200

           Responce URL http://static.bbci.co.uk/frameworks/barlesque/2.59.1/orb/4/script/orb.js:
           Status 200

    1 scenario (1 passed)
    3 steps (3 passed)
    0m5.678s

###  What can we do with Network Traffic

Well, Sky is the limit ! You can lots of fancy things with captured network traffic. Like

  * Check whether CSS, JS, Modules, Images loaded on the page. 
  * Check for any 404 or other error on the page
  * Check for the particular query string in the response body

### Source Code on GitHub

You can find GitHub Repository 'poltergeist-network-traffic'

####  Video Demo

Watch out Video Demo:

## Setting up Headless Travis CI build with Cucumber+Capybara+Poltergeist

### Travis CI

Travis CI is a continuous integration service for the open source projects hosted on GitHub. You can login into  TravisCI with your existing GitHub account. Travis CI build will run after every checkin into the GitHub. Typically TravisCI loos like this

### Setting up TravisCI +Poltergeist

Setting up Travis CI for the Cucumber Poltergeist project is easy task as PhantomJS is pre-installed on the TravisCI. Poltergeist uses PhantomJS as a headless browser to execute UI Cucumber+Capybara scenarios. If you haven't came across Cucumber+Capybara+Poltergeist setup, please read my previous post ' Cucumber + CapyBara + Poltergeist: Rockstar BDD Combo'

Now, let's setup the TravisCI for the one of the Poltergeist project on GitHub: Poltergeist-Demo

**Poltergeist is a awesome driver for Capybara. Poltergeist is based on headless PhnatomJS. This repository is a demo of Poltergest and Cucumber.**  
<https://github.com/Shashikant86/Poltergeist-Demo>  
3 forks.  
0 open issues.  
Recent commits:

  * Updating Rakefile, Shashikant86
  * Travic CI config fix for Gemfile, Shashikant86
  * Travic CI config fix for Gemfile, Shashikant86
  * Travic CI config fix for Gemfile, Shashikant86
  * Travic CI config fix for Gemfile, Shashikant86

I have logged into TravisCI with my GitHub account. You can view this public build here

Now, we need to create '.travis.yml' file in the root of the project.

    language: ruby
    cache: bundler

    rvm:
      - 1.9.3

    before_script: 'bundle install'
    script: 'bundle exec cucumber'

    branches:
      only:
        - master

    notifications:
      email:
        - shashikant.jagtap@aol.co.uk

Now that, we have created '.travis.yml' file with Ruby version and script to be executed on the TravisCI server. You can learn more about Ruby setup on TravisCI here

Once you got your Poltergeist scenarios working on local machine then you are done. TravisCI build will trigger after every commit to GitHub.

I have made commit by updating Rakefile and build has started on TravisCI:

 Now that build has started and installing all the RubyGems as shown in the screen above. It will use pre-installed PhantomJS to execute scenarios using Poltergiest driver.

Now it will execute all the scenarios in the project in the headless driver.

You can see full text logs of the execution of this build here

#####  Conclusion

TravisCI can be used for running automated acceptance scenarios using PhantomJS as it's pre-installed headless browser. PhantomJS can be driven by combination of the Cucumber+Capybara+Poltergeist.

## BDD Code analysis with Cucumber and Cuke_Sniffer

### BDD Code

Behavior Driven Development a.k.a BDD is a recent and modern software development agile framework. While writing software using BDD, we use different tools but code is structured in similar way. It consist of following

  * ### Feature Files

Feature files are the set of features/stories and scenarios in it. Feature files are generally written in the business readable Domain Specific Language DSL] called "[Gherkin". Gherkin use 'Given When Then' a.k.a GWT format for the scenarios. The feature file has .feature extension. Gherkin can be understood by most of the BDD tools. The feature file may look like this

    Feature: Sports
      In order to know about different sports
      As a sport fan
      I want list of some sports

    Scenario: List of the sports
      Given the system knows about the following sports::
        | name     | player           |
        | Cricket  | Sachin Tendulkar |
        | Tennis   | Andy Murray      |
        | FootBall | David Beckham    |
      When the client requests GET /sports
      Then response should be "200"
      And the JSON response should be an array with 3 "name" elements
      And response should be JSON:
       """
      [
      {"name": "Cricket", "player": "Sachin Tendulkar"},
      {"name": "Tennis", "player": "Andy Murray"},
      {"name": "FootBall", "player": "David Beckham"}
      ]
      """

  * ### Step Definitions

The step definitions is the code which glue the gap between business logic and technical aspect. This code makes Gherkin feature work. The step definitions can be written in the different language. The example for the step definition file with Cucumber and Ruby for the above feature file.

    When /^the client requests GET (.*)$/ do |path|
            get(path)
    end

    Then /^response should be JSON:$/ do |json|
            JSON.parse(last_response.body).should == JSON.parse(json)
    end

    Then /^response should be "([^"]*)"$/ do |status|
        last_response.status.should == status.to_i
    end

    Then /^the JSON response should be an array with (\d+) "([^"]*)" elements$/ do |num, name|
    page = JSON.parse(last_response.body)
      page.map { |d| d[name] }.length.should == num.to_i
    end

  * ### Support Code

The support code consist of configuration of the environment and driver  (selenium, phantomjs etc ) for the web acceptance framework. The example of the support code file for the cucumber (env.rb)

    require File.join(File.dirname('__FILE__'), 'sports_app')
    require 'rack/test'
    require "Capybara"
    require "Capybara/cucumber"
    require "rspec"
    require 'capybara/poltergeist'

    Capybara.default_driver = :poltergeist
    Capybara.register_driver :poltergeist do |app|
        options = {
            :js_errors => false,
            :timeout => 120,
            :debug => false,
            :phantomjs_options => ['--load-images=no', '--disk-cache=false'],
            :inspector => true,
        }

        Capybara::Poltergeist::Driver.new(app, options)
    end

    module AppHelper
            def app
                    SportsApp
            end
    end

    World(Rack::Test::Methods, AppHelper)

  * ### Hooks

Hook is the piece of code that can be run before or after each scenario, feature, suite or step. There are different types of hook. [hook.rb]

    Before do 
            SportsApp.data = []
    end

    After do 
            puts "Go To Bed"
    end

  * ### Config

The config file can be used to set profile with which we can run our features. This file can also used to generate reports. [cucumber.yml

    default: --profile html_report --profile rack
    html_report: --format progress --format html --out=report/features_report.html
    rack: --tags @rack

  * ### Dependencies

There are different dependency management system for different programming languages. e.g Composer for PHP, bundler for Ruby.

We have example 'Gemfile' where we declare all our dependencies.

    source 'http://rubygems.org'

    gem 'sinatra', '1.3.1'
    gem 'json', '1.6.3'
    gem 'cuke_sniffer'
    gem "poltergeist"

    group :test do 
            gem 'cucumber', '1.1.3'
            gem 'rspec', '2.7.0'
            gem 'rack-test', '0.6.1'
    end

### Report

This may be optional but you can create a directory for storing html reports and other reports like cuke_sniffer reports. On CI boxes, you can create and delete these directories temporarily.

BDD code structure for me looks like this in my Sublime Text

###  BDD Code Analysis with Cuke Sniffer

  Cuke_sniffer is the ruby gem and can be used for the code analysis for any cucumber project.

### Installation

In order to use Cuke_Sniffer' you need to have ruby version above 1.9.3.

    $ gem install cuke_sniffer

Or Simply add this to your projects 'Gemfile'

      gem 'cuke_sniffer'

Now update the bundle

    $ bundle install

You are done  and ready to use cuke_sniffer.

## Usage

### Now navigate to your project where features directory is located and run

    $ cuke_sniffer

When I run it with demo project, I got

We can generate Cuke_sniffer html reports like this

    $  cuke_sniffer --out html report/cuke_sniffer.html

This will generate html report and for the code analysis.

### Benefits of Cuke_sniffer

  * Cuke_sniffer analyses all feature file, step definitions and hooks for improvements
  * Cuke_sniffer tells us about any dead steps
  * Cuke_sniffer detect smells in the feature files and step definitions
  * Cuke_sniffer detect how many times hooks are used

#### GitHub

Source code of this demo is available on the GitHub

Cuke_sniffer_demo

HTML Report can be found here.

#### Conclusion

Cuke_sniffer can be used in the any Cucumber project for better BDD code and improve code continuously.

## Speed up BDD with Parallel Cucumber

### Running Cucumber in Parallel

First of all, if you using Cucumber as a BDD tool and having large feature set, then you are at the right place.  Now we have an awesome Ruby Gem called 'Parallel_tests' which is going to make our life much easier by parallelising large set of feature to run much faster. You can read more 'Parallel_tests' on GitHub.

In this short tutorial, we will see how to use 'Parallel_tests' in our project and how to aggregate generated html cucumber reports.

We will use source code from my GitHub repository 'Cuke_Experiment'. Please download source code if you have development environment ready

    $ git clone https://github.com/Shashikant86/Cuke_Experiment
    $ cd Cuke_Experiment

You need to have Ruby 2.0.0 for this demonstration.

### Using Parallel_Tests Gem

Parallel_Tests is a Ruby Gem for running RSpec, Cucumber and Test::Unit on multiple CPUs in the parallel to speed up tests. There are many benefits using Parallel_Tests Gem into your Cucumber.

  * It is very easy to use in your existing project or test suite
  * Parallel Tests forks cucumber into number of CPUs processes and you can specify number of processes.
  * Parallel Tests can generate separate reports for each process using variable 'ENV['TEST_ENV_NUMBER']'
  * You don't need to change your test options. Just keep everything inside   _'-o "your test profiles'_

### Installing Gem

You can just run following command to install parallel_tests gem into your existing project

    $ gem install parallel_tests

OR Simply add it in your Gemfile.

    $ vim Gemfile

And add following line

    gem "parallel_tests"

Now, you need to install bundler.

    $ bundle install

That's it. You are now ready to use parallel_tests into your project.

### Using Gem

Once you have successfully installed parallel_tests Gem then you are now ready to use it. By default, it forks cucumber into 4 processes depending on number of feature files. If number of feature files are less than 8 then it usually use 2 processes.

    $ bundle exec parallel_cucumber features/

Now that, this command will run all your feature files within the _'features'_ directory.

### Running features from sub-directories

You can run specific set of features from sub-directories by navigating to that directory.

    $ bundle exec parallel_cucumber features/homepage_features/

### Running features with specific profiles or tags

You can run parallel_tests y using specific profiles or tags using test options  '- o'

    $ bundle exec parallel_cucumber features/ -o "-p stage -t @sanity"

###  Running features by specifying number of processes

You can specify number of processes to speed up feature executions by using option '-n'

    $ bundle exec parallel_cucumber features/ -n 8

This will break down features into 8 different processes.

### Generating HTML Reports

We can easily generate HTML reports for the each process and aggregate reports for each process. As we said earlier that there is a variable ENV['TEST_ENV_NUMBER'] which gives details about all the process that cucumber scenarios are executing.

In order to generate reports for all the processes, we need to create a profile in our 'cucumber.yml'. Let's call this profile 'default' profile.

    default: --format html --out report<%= ENV['TEST_ENV_NUMBER'] %>.html

This will create HTML report for each process and name it as report.html, report2.html and so on.

#### Source Code & Quick Start

Source code available on GitHub 'Cuke_Experiment' , Download it and get started. I assume, you have Ruby development environment ready(RVM, XCode, Homebrew etc etc)

    $ git clone https://github.com/Shashikant86/Cuke_Experiment
    $ cd Cuke_Experiment
    $ rvm use 2.0.0
    $ bundle install
    $ bundle exec parallel_cucumber features/

It will execute all the features in 2 different processes and generate report.html and report2.html. My i-Term look like this:

#### Watch Video Demo

You can watch in action in the following Video

HAPPY BDD !!

## Living Documentation in the BDD with Relish

### BDD and Living Documentation

Bridging the communication Gap between Business and Technology is a main goal of the Behaviour Driven Development [BDD]. By adopting practices of BDD , we can write scenarios in human readable language so that non-technical people can understand scenarios and specifications. It's always good idea to have scenarios in human readable language but there is a issue, where to write down those scenarios?. Here are few possible solutions that  you may think of

  * Write down scenarios on Paper so that business people can read.
  * Write scenarios in the Collaborative Tools like Mingle, JIRA and tell business people to have a look.
  * You are free to keep it in the Source Control like SVN or Git.
  *  Use traditional approach like Excel sheets, Spreadsheets and keep it in the Google Docs or DropBox.

I am sure that, none of above is going to work well. " _Business people like to use mouse than keyboard_ ". They like a nice, user friendly interface. Living Documentation is the solution to all these problems.

Living Documentation is a dynamic document which can be edited, updated and accessed collaboratively within the team. BDD enforces that your Feature files should serve as documentation. Anyone should understand system's behaviour by reading your feature file.

### Introduction to Relish

Relish is a awesome tool developed by Matt Wynne [@mattwynne] in order to host your feature files online. Relish is a easy to use tools and you can share feature files just by sharing links to your Relish project. Here are some cool feature features of the relish

  * Easy to use and install
  * Work with many BDD tools which supports Gherkin [ Behat, Cucumber, SpecFlow, etc etc ]
  * You can create multiple projects
  * Option to keep your projects private
  * Check for Gherkin Syntax error while pushing online.
  * Browser other public projects online & custom documentation with readme.md file.

There are more features to come. You can follow @relishapp on Twitter for more news and updates.

### Get Started with Relish

In order to get started with Relish, you need to signup for the Relish by providing your email address. Once you signed up, you need to create Publisher in order to create your first project. You will guided well on the website. Here  is how ,I have created publisher for myself.

### Install  Relish

Once you done with creating publisher. Its very easy to install Relish. You need to have RubyGems installed. You can simple run

    sudo gem install relish

I got something like this :

### Add Relish Project

Once you installed Relish then you can your projects to relish. I have a 'BehatDemo' project hosted on GitHub. So I will add same project to Relish. You need to provide Relish Credentials at this point i.e email address and pasword.

    relish projects: add Shashikant86/BehatDemo

I have  project added to relish.

### Push Your Features Online

Now that, we have created out Project on Relish. We need to push our feature files to that project. Navigate to your project path and push features online. Relish will look for 'features' directory and send all features online

    $ cd /path/to/your/project
    $ relish push Shashikant86/BehatDemo

You will get something like this:

### Share

Once you have pushed your features online, you can just share link to look at features file with easy and nice looking interface. The feature file we just pushed is averrable at Relish App project  Shashikant86/BehatDemo

#### Conclusion

Relish makes living documentation easy within the BDD project. You can host your projects and BDD feature files online and share with business people to read and contribute.

## BDD: Auto-push living documentation with Relish

### Relish

Relish is a cool tool for the living documentation in the BDD projects. Please my detailed blog about how to setup relish-living documentation in the BDD project. Relish can be used with any BDD tool which support Gherkin language. In this post, we will see how to auto-push feature files with relish.

### Get Relish API Token

In order to push feature files automatically with relish, you need to have relish account. Once you logged into the Relish, you can get your API token by visiting by

  * Log in into Relish with your credential 
  * Visit 'https://www.relishapp.com/api/token' url.

This url will return a string, that's your API token.

### .relish

Once you got your API token, We can create '.relish' file in our BDD project.

    $ vim .relish

    --- 
    api_token: {your_api_token}

This file will automatically detect your credentials and push the feature files with 'relish push' command.

    $ relish push Publisher_name/project_name

You can setup a script which run periodically on continuous integration server to regularly push feature files online.

Happy BDD

## RestFul API Testing with Cucumber and Rack Test

### API Testing & BDD

API Testing is a nice way to conduct end to end test on your application by communicating with another modules. You can read more about it here

When it comes to Behaviour Driven Development [BDD], API testing become more interesting. I am having great fun experimenting with Cucumber while reading Cucumber Book by Matt Wynne & Aslak Hellesoy. I already tried API Testing with Behat by following Keith Loy 's blog 'Testing Rest API with Behat' which you can read here.

In this short, tutorial, we will see in-process API Testing with Cucumber and Rack Test. We have assumed that Cucumber and Application sits in the same Ruby process. We will be dealing with simple API which stores and returns name of sports and players.

### Start with Feature File

We will create simple web Service by using Sinatra and JSON which has /sports route and returns data in JSON format.  Lets Create Project and within that project we will create 'sports_list.feature'

    $ sudo mkdir REST-Cucumber-RackTest
    $ cd REST-Cucumber-RackTest
    $ vim sport_list.feature

Let's add following code to the 'sport_app.rb' file

    Feature: Sports
      In order to know about different sports
      As a sport fan
      I want list of some sports

    Scenario: List of the sports

    Given the system knows about the following sports::
    | name        | player           |
    | Cricket     | Sachin Tendulkar |
    | Tennis      | Andy Murray      |
    | FootBall    | David Beckham    |
    When the client requests GET /sports
    Then response should be "200"
    And the JSON response should be an array with 3 "name" elements
    And response should be JSON:
    """
    [
      {"name": "Cricket", "player": "Sachin Tendulkar"},
      {"name": "Tennis", "player": "Andy Murray"},
      {"name": "FootBall", "player": "David Beckham"}

    ]
    """

In here, we are storing some sports and players, then make GET request /sports which should return 200 response. We are also checking number of elements and response body.

Now we will install necessary Gems. Create 'Gemfile' with following gems

    source 'http://rubygems.org'
    gem 'sinatra', '1.3.1'
    gem 'json', '1.6.3'

    group :test do 
            gem 'cucumber', '1.1.3'
            gem 'rspec', '2.7.0'
            gem 'rack-test', '0.6.1'
    end

Install Gems by running command

    $ bundle

Now we can run 'cucumber' and you will see following

    Shashi-MacBook-Pro:REST-Cucumber-RackTest user$ cucumber
    /Users/user/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.3.4/lib/bundler/runtime.rb:216: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    Feature: Sports
      In order to know about different sports
      As a sport fan
      I want list of some sports

      Scenario: List of the sports                                      # features/sports_list.feature:6
        Given the system knows about the following sports::             # features/sports_list.feature:8
          | name     | player           |
          | Cricket  | Sachin Tendulkar |
          | Tennis   | Andy Murray      |
          | FootBall | David Beckham    |
        When the client requests GET /sports                            # features/sports_list.feature:13
        Then response should be "200"                                   # features/sports_list.feature:14
        And the JSON response should be an array with 3 "name" elements # features/sports_list.feature:15
        And response should be JSON:                                    # features/sports_list.feature:16
          """
          [
            {"name": "Cricket", "player": "Sachin Tendulkar"},
            {"name": "Tennis", "player": "Andy Murray"},
            {"name": "FootBall", "player": "David Beckham"}

          ]
          """

    1 scenario (1 undefined)
    5 steps (5 undefined)
    0m0.018s

    You can implement step definitions for undefined steps with these snippets:

    Given /^the system knows about the following sports::$/ do |table|
      # table is a Cucumber::Ast::Table
      pending # express the regexp above with the code you wish you had
    end

    When /^the client requests GET \/sports$/ do
      pending # express the regexp above with the code you wish you had
    end

    Then /^response should be "([^"]*)"$/ do |arg1|
      pending # express the regexp above with the code you wish you had
    end

    Then /^the JSON response should be an array with (\d+) "([^"]*)" elements$/ do |arg1, arg2|
      pending # express the regexp above with the code you wish you had
    end

    Then /^response should be JSON:$/ do |string|
      pending # express the regexp above with the code you wish you had
    end

In order to make them pass, we need to

  * Create Simple Web service which returns JSON 
  * Organize our Project Code with Step Definitions & Support directory
  * Implement Step Definitions to make them pass

Create a Project Structure by creating files and directory which will look like this :

#### GitHub

We have source code available on the GitHub in the repository 'REST-Cucumber-RackTest'. You can clone source code and execute following commands to see all the scenarios passing:

    $ git clone https://github.com/Shashikant86/REST-Cucumber-RackTest
    $ cd REST-Cucumber-RackTest
    $ bundle
    $ cucumber

####  What We have Done?

Let's try to understand what we have done in each of these files in order to make all steps passed.

### sports_app.rb

In this file, we are creating simple web service with route /sports which will return JSON response. We are using Sinatra for creating the web service.

### features/support/env.rb

As we are calling Rack-Test's 'get' method, we need to setup 'environment for the Rack-Test. The 'get' method is defined in the in a module called "Rack::Test::Methods".

Last line of the code in this file

    World(Rack::Test::Methods, AppHelper)

This will register two ruby module within Cucumber one for HTTP Simulation and other for own helper module. We have defined AppHelper to communicate between modules.

### features/support/hooks.rb

In here, we are clearing data in the 'before' hook. We have stored data in the class variable that needs to be cleaned up every time.

### features.step_definitions/rest_steps.rb

This is the place where we have implemented all the REST related steps. We have parsed JSON response also we have checked status of the message and number of elements.

### features.step_definitions/sports_steps.rb

In this step, we have stored data in the class variable.

At this point, if you run 'cucumber' you will see all steps passed.

    Shashi-MacBook-Pro:REST-Cucumber-RackTest user$ cucumber
    /Users/user/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.3.4/lib/bundler/runtime.rb:216: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    Feature: Sports
      In order to know about different sports
      As a sport fan
      I want list of some sports

      Scenario: List of the sports                                      # features/sports_list.feature:5
        Given the system knows about the following sports::             # features/step_definitions/sports_steps.rb:2
          | name     | player           |
          | Cricket  | Sachin Tendulkar |
          | Tennis   | Andy Murray      |
          | FootBall | David Beckham    |
        When the client requests GET /sports                            # features/step_definitions/rest_steps.rb:2
        Then response should be "200"                                   # features/step_definitions/rest_steps.rb:10
        And the JSON response should be an array with 3 "name" elements # features/step_definitions/rest_steps.rb:14
        And response should be JSON:                                    # features/step_definitions/rest_steps.rb:6
          """
          [
            {"name": "Cricket", "player": "Sachin Tendulkar"},
            {"name": "Tennis", "player": "Andy Murray"},
            {"name": "FootBall", "player": "David Beckham"}
          ]
          """

    1 scenario (1 passed)
    5 steps (5 passed)
    0m0.056s

### Conclusion

Using Cucumber and Rack Test, we can perform API testing within te same Ruby process. We will see API testing in the 'Out-of-Process' in the next post. Stay tuned !!

## Cucumber Tip - Skip HTTP Auth with capybara and headless Drivers

### HTTP Authentication

HTTP authentication is a mechanism of force use to user credential before entering into the website. While developing application, we might need to use HTTP authentication to restrict unauthorised user accessing site. You can read more HTTP auth

While automating the pages with HTTP authentication we need to enter the login credentials to carry on test journey. Here is something we can do to skip HTTP auth

### Set HTTP Headers

Headless capybara drivers provides mechanism to set HTTP headers before visiting page which skips http authorisation. There are Poltergeist and Mechanize  drivers for the capybara which allows us to set HTTP header. You can add those steps in the before hook.

### Using Poltergeist

You can set HTTP header with Poltergeist to skip basic http auth like this. You need base64 for this

    page.driver.headers = {'Authorization': 'Basic '+ Base64.encode64('username:password')};

### Using Mechanize

You can set headers using mechanize like this:

    page.driver.browser.agent.auth('username', 'password')

It become so simple to skip basic http auth using headless drives like Poltergeist and Mechanize.

Happy BDD

## HTTP Status code of multiple URLs from Text file

### HTTP Status Codes

There might be few tools available in the market which can be used for checking HTTPS codes for the urls. It would be an awesome to check HTTP status code  if we can have txt file with list of urls.

Now, we will see a how to check HTTP status code of the urls available in the txt file.

### BASH Script

Now, Let's write small bash script which will take txt file as an argument checks for the HTTP response code.

    $ vim file_url_status

And following bash code to the file

    FILE="$1"
    while read LINE; do
      curl -o /dev/null --silent --head --write-out '%{http_code}' "$LINE"
      echo " $LINE"
    done < ${FILE}

This script is checking each line in the FILE and prints HTTP_CODE of the url.

Now, Let's create a text file 'url.txt' with list of urls

    $ vim ur.txt

Now insert following urls

    http://www.bbc.co.uk

    http://www.aol.co.uk

    http://www.facebook.com

    http://www.google.com

Change the mode of both the files

    $ sudo chmod 777 file_url_status
    $ sudo chmod 777 url.txt

Now, you can execute the bash script

    $ ./file_url_status url.txt

You will see an output something like this :

    200 http://www.bbc.co.uk
    200 http://www.aol.co.uk
    301 http://www.facebook.com
    302 http://www.google.com

i-Term will look like this :

Using a small bash script, we can check HTTP_CODE of the multiple urls stored in the text file.

## Automated Accessibility with Cucumber and Capybara-Accessible

### Automated Web Accessibility

Automated web accessibility checks plays important role in order to make website accessible to the people with disabilities. Accessibility testing can be done in the different ways and using different techniques but while plugging them into the BDD tools like Cucumber is good fun.

In this post, we will see how we can use 'capybara-accessible' Rubygem in order to check accessibility of the website.

### Capybara-Accessible

Capybara-accessible is a RubyGem which uses Google Accessibility Developer tool in order to check website against Google's accessibility standards audit rules.

### Using Gem

In order to use capybara-accessible gem, you just need to include it in your Gemfile and update bundle

Note: You also need to have 'selenium-webdriver' gem in order to get capybara-accessible working

    gem "selenium-webdriver"
    gem "capybara-accessible"

Then you just update bundle

    $ bundle install

Now you need to update your 'features/support/env.rb' file with below code

    require 'capybara/rspec'
    require 'capybara/accessible'

    Capybara.default_driver = :accessible

This will use default capybara driver accessible.

You can then run 'cucumber' to see the result.

### capybara-accessible In Action

Let's create a feature file to test accessibility of the Google Home page and BBC home page

    $ vim accessibility.feature

and add following feature

    Feature: Accessibility 
      As a user
      I want website to be accessible
      So that I can access it wthout hassle

    Scenario: BBC Accessibility

      Given I am on the BBC home page
      Then I should see page meet all accessibility criteria

    @inaccessible    
    Scenario: Google HomePage Accessibility

      Given I am on the Google home page
      Then I should see page meet all accessibility criteria

Now you can add step_definitions by using capybara library  in the 'features/step_definitions/google_steps.rb'

    Given(/^I am on the Google home page$/) do
    puts  visit "http://www.google.com"
    end

    Given(/^I am on the BBC home page$/) do
    puts  visit "http://www.bbc.co.uk"
    end

    Then(/^I should see page meet all accessibility criteria$/) do

    end

You  are now good to run cucumber to perform accessibility check

    $ bundle exec cucumber

I saw something like this

**Why Google Scenario is tagged as @inaccessible  **

Google scenario is failing if we don't tag it as @inaccessible. Error looks like this

    Feature: Accessibility

      As a user
      I want website to be accessible
      So that I can access it wthout hassle

      Scenario: Google HomePage Accessibility                  # features/accessibility.feature:13
        Given I am on the Google home page                     # features/step_definitions/google_steps.rb:2
          Found at https://www.google.co.uk/?gws_rd=cr&ei=mHE7UpXPGemm0wWu1YHQDA

          *** Begin accessibility audit results ***
          An accessibility audit found
          Errors:
          Error: AX_TEXT_01 (Controls and media elements should have labels) failed on the following element:
          #gbqfq
          See https://code.google.com/p/accessibility-developer-tools/wiki/AuditRules#AX_TEXT_01:_Controls_and_media_elements_should_have_labels for more information.

          Warnings:
          Warning: AX_FOCUS_01 (These elements are focusable but either invisible or obscured by another element) failed on the following element:
          #viewport > A
          See https://code.google.com/p/accessibility-developer-tools/wiki/AuditRules#AX_FOCUS_01:_These_elements_are_focusable_but_either_invisible_o for more information.

          Warning: AX_TEXT_02 (Images should have an alt attribute) failed on the following element:
          #pmocntr2 > TABLE > TBODY > TR:nth-of-type(2) > .padi > IMG
          See https://code.google.com/p/accessibility-developer-tools/wiki/AuditRules#AX_TEXT_02:_Images_should_have_an_alt_attribute,_unless_they_hav for more information.

          *** End accessibility audit results *** (Capybara::Accessible::InaccessibleError)
          ./features/step_definitions/google_steps.rb:3:in `/^I am on the Google home page$/'
          features/accessibility.feature:15:in `Given I am on the Google home page'
        Then I should see page meet all accessibility criteria # features/step_definitions/google_steps.rb:27

    Failing Scenarios:
    cucumber -p pretty features/accessibility.feature:13 # Scenario: Google HomePage Accessibility

    1 scenario (1 failed)
    2 steps (1 failed, 1 skipped)
    0m5.743s

We have a hook that skips scenarios for accessibility check.

    Around('@inaccessible') do |scenario, block|
            Capybara::Accessible.skip_audit { block.call }
    end

So the hook skips the Google scenario for the accessibility check.

### Try it Yourself

You can find source code for the demo on Github

Cuke_Experiment

    $ git clone https://github.com/Shashikant86/Cuke_Experiment
    $ cd Cuke_experiment
    $ bundle install
    $ bundle exec cucumber features/accessibility.feature

You can add automated accessibility checks with BDD tool Cucumber using 'capybara-accessible'. Thanks to @ckundo

Watch Here

# BDDFire: Instant Ruby Cucumber Capybara

## Introducing BDDfire : An Instant Ruby-Cucumber BDD Framework

### BDDfire

I am glad to announce ' **BDDfire**' : An instant Ruby-Cucumber BDD framework which supports various popular open-source libraries like Capybara, Selenium-WebDriver, Poltergeist, Relish, Cuke_sniffer, Rubocop, Appium, Saucelabs, Browserstack etc etc.BDDfire will create all the directories and required files to support the latest open-source libraries in the Ruby-Cucumber framework.

BDDfire is a rubygems and we can install and use it in any brand new Cucumber project or existing Cucumber framework.

BDDfire source code is available on the Github. In this post, we will explore BDDfire in the detail.

### BDDfire Features

Cucumber is a very popular BDD framework. Cucumber become more effective when it's plugged with other open -source libraries. Sometime we miss most of the useful libraries to be used with Ruby-Cucumber. BDDfire supports lots of modern open-source libraries  so that we won't miss new trends in the world of Ruby-Cucumber.

BDDfire has following features:

  * BDDfire will create template directories and files for the Cucumber project.
  * Capybara and WebDriver Integration for executing acceptance scenarios in the real browsers
  * Capybara and Poltergeist integration to execute scenarios in the headless browsers.
  * Generate template directories to support RSpec
  * BDDfire supports cuke_sniffer and Rubocop libraries which detect smell in the Ruby-Cucumber framework.
  * BDDfire supports Relish for the living documentation.
  * Rakefile has been automatically created as a part of BDDfire
  * BDDfire  supports YARD documentation of the cucumber project.
  * BDDfire allow you write steps using Page Object Pattern

### BDDfire Installation

With BDDfire, you can install Ruby-Cucumber BDD framework with all those libraries in a single command.

    $ gem install bddfire

Or  include BDDfire in the Gemfile

    gem 'bddfire'

Once installed we can make use of the BDDfire in our existing project. BDDfire commands will be listed when you run 'bddfire'

    $ bddfire
    Commands:
      bddfire fire_cucumber   
      bddfire fire_rspec     
      bddfire generate_yard  
      bddfire help [COMMAND]  
      bddfire version

The commands will look like this in the terminal.

### BDDfire Usage

Now that, we have installed BDDfire. We need to create Ruby-Cucumber framework and make use of it.

### Generate & Install Ruby-Cucumber Framework

BDDfire will install entire Ruby-Cucumber BDD framework in a single command

    $ bddfire fire_cucumber

This will create all the directories and the files with required code in it. This will create Gemfile and Rakefile if they are not already in the project. Th typical output will look like this :

Now that we have got new Gemfile. We need to install bundle to get the dependencies installed on our project.

    $ bundle install

This will create a 'Gemfile.lock' file. Now our Ruby-Cucumber Framwork looks like this

### Using Selenium-WebDriver

Now we have installed 'Selenium-Webdriver' and in the cucumber.yml file, we have selenium as a 'default' profile. We can execute our scenarios using

    $ bundle exec cucumber

### Using Headless Poltergeist

Poltergeist is the headless driver for the Capybara. We have created a profile for the Poltergeist in the cucumber.yml. Poltergeist execute scenarios in the headless browser based on PhantomJS

    $ bundle exec cucumber -p poltergeist

### Using Relish

Relish allows us to push feature file online as a living documentation. We have already got '.relish' file in out BDDfire framework. We need to get relish api token. You need to have relish account and project created in the relish. Please use my previous blog to setup Relish.

Now you can push all the features to relish :

    $ bundle exec relish push {Publisher}/{project}

### Using Cuke_Sniffer

Cuke_Sniffer is a library which detects smell in the cucumber project. You can refer previous blog about cuke_sniffer to get detailed installation and usage.

    $ bundle exec cuke_sniffer

### Using Rubocop

Rubocop is the library to detect smell in the Ruby code. We have installed rubocop can be executed like this :

    $ bundle exec rubocop

### Using Cloud Testing Frameworks

Saucelabs, Testingbot and Browserstack are the cloud testing framework. You need to have Saucelabs/Testingbot/Browserstack account and API key to use it. We have Capybara driver register 'features/support/env.rb'. We need to add Saucelabs/Testingbot/Browserstack related details.

    $ bundle exec cucumber -p browserstack

Testingbot

    $ bundle exec cucumber -p testingbot

Saucelabs

     $ bundle exec cucumber -p sauce

### Using Appium

Appium is a very popular mobile test automation framework. You can refer my previous post to more about Cucumber-Appium setup. Make sure you have required setup before using Appium. Here we have 'package.json' file. You need have NodeJS installed so that we can install Appium

    $ npm install

This will install Appium in the 'node_modules' directory. We can then start Appium Server.

    $ ./node_modules/.bin/appium

Now that we can run cucumber cucumber

    $ bundle exec cucumber -p appium

### Using Rake Tasks

BDDfire creates some rake tasks by default. We have a Rakefile which has three tasks. Rake task 'features' will execute all the features with selenium deiver. Rake task ' cuke_sniffer' and 'rubocop' execute bundles for relevant libraries.

    $ bundle exec rake features
    $ bundle exec rake cuke_sniffer
    $ bundle exec rubocop

### CI Integration

Currently, you can use the script 'ci_script' on Jenkins or Hudson. You need pass rake rask to the script

    $ ./ci_script features

### Page Object Pattern

BDDfire allows us to write steps using  Page Object Pattern. Page object pattern is great way to maintain the automation framework by abstracting locators and common methods to the Page classes. BDDfire has created directory called "features/pages" which has 'Abstract.rb' and 'HomePage.rb" files. We can create instance of these classes at any point in the steps_definitions like this :

    @home_page = HomePage.new(Capybara.current_session)
    @home_page.visit_home_page

This makes our step_definitions more stable. We need to change page classes if something changed and step_definitions remains unchanged.

### Contributing to BDDfire

I bet, you have better ideas to contribute to BDDfire. You can fork the repo on the github. Things to do are

  * Adding pre-defined steps for the Poltergeist and Selenium Driver. User will utilise step_definitions from BDDfire.
  * Adding steps for Appium
  * And many many things

**BDDfire: Instant Cucumber-BDD framework. Automate Mobile & Web apps with less code**  
<https://github.com/Shashikant86/bddfire>  
3 forks.  
1 open issues.  
Recent commits:

  * Changed Appium Driver config, Shashikant86
  * Fixed Chrome driver, Shashikant86
  * Added Mobile and Web drivers, Shashikant86
  * Added headless steps for Poltergeist, Shashikant86
  * Updated Gem Description, Shashikant86

Watch Here

## BDDfire [Refactored] : Automate Web and Native Mobile Apps with less code

### Refactored BDDfire

As of now, BDDfire become popular as instant Ruby-Cucumber-Capybara BDD framework. It got published in the 'Methods and Tools' magazine and since then number of downloads has been increased dramatically. Now BDDfire ha mor tha 30,000 downloads. BDDfire has been also published as big link on DZone.

> BDDfire: Instant Ruby Cucumber Framework – <http://t.co/Cl28jaqrbq> – @DZoneLinks Big Link by martinig
> 
> — DZone Links (@DZoneLinks) April 2, 2015

Previously BDDfire was just creating skeleton framework for the Ruby-Cucumber-Capybara BDD framework. Now, it has more than that. Let's explore what's new in the BDDfire and what will be the future of BDDfire.

### What's New ?

New version of of the BDDfire has some amazing features. It includes some predefined steps and enhanced Appium support

### Improved Skeleton

Now  that BDDfire generates skeleton project with all required files and directories with more interactive way. It will show you information about which file or directory is being created. BDDfire will create a 'cucumber' directory and put everything inside it.

    $ bddfire fire_cucumber

The new output will  now look like this :

### Build-In Steps: Code Less

BDDfire has added in-built steps definitions for the selenium and poltergeist driver so that you don't need to implement step definitions for those steps. You can find predefined UI steps here and predefined steps specific to Poltergeist headless driver here

### Improved Appium Driver

BDDfire has refactored Appium driver completely. Now we ca use all Appium related capabilities. Here's a details of the change on github.  iOS an Android related capabilities can be used as per need. You can always disable not required capabilities by commenting the lines.

### TODO

Now BDDfire needs some mobile steps as a pre-defined steps so that we can automated mobile apps with less hassles. Feel free to fork BDDfire and contribute to it

# Mobile Test Automation

## iOS Automated Testing in the BDD with Cucumber, Appium and SauceLabs

The mobile  automation is becoming trending topic these days. There are new tools introducing in the market in order to make the iOS and Android automation hassle free and Appium is one of them.

In this tutorial, we will see how to setup Mac OSX for iOS automation using BDD tool [Cucumber], cloud testing service Saucelabs and Appium server.

### Appium

Appium is a open source, cross platform test automation tool for the hybrid and native iOS, Andriod and FirefoxOS apps. In the simple term, appium is a server running in the background like Selenium server. The key benefit of the Appium

  * It's very easy to setup and on different platform.
  * Can write tests in the language of your choice (Ruby, Python, Java, PHP, Node)
  * Can still use Selenium Wbdriver JSON wire protocol 
  * Don't need to re-compile Mobile app on different platform

You can read more about Appium on Appium-Github page.

### Setting up Mac OSX for iOS Automation

Now that, we need to set up our Mac OSX for iOS automation with Cucumber and Appium. There are few tools we need to install in advance before we go ahead with the iOS automation, make sure you have met following requirements

  * OS X 10.8.4 or later
  * Xcode 4.6.3 or later
  * Node and npm (brew install node) (Node must be >= v0.8)

### Setting up Cucumber-Ruby environment

There is a nice blog post to setup Mac OXS with Ruby-ish tools  [Moncef's blog.] Basically, you need to install following tools and services.

  * Xcode with Command line Tools
  * Various versions iOS Simulators. [ It comes with Xcode]
  * Homebrew [Package Management ]
  * Git
  * RVM and Ruby gems
  * Cucumber

Please follow the steps in the @monfresh 's blog and you will have the above tools installed in your Mac OSX. On top of that you need to install few other tools.

**Install NPM**

Install npm using HomeBrew

    $ brew update ;\
      brew upgrade node ;\
      brew install node

This will install  node.js package management system.

Install some node pakages

  * Install Grunt

    $ npm install -g grunt grunt-cli

  * Install appium

    $ npm install -g appium

  * Install wd

    $ npm install wd

You can follow steps in appium-ruby-console-osx to get everything setup for you.

### Setting up Appium

You can install Appium with the following options:

**Option 1 : Appium OSX App**

If you are on Mac OSX, I would strongly recommend to download Appium dmg.

You can then run app in your Mac and launch server by setting up port and providing suitable app path. Once you click on 'Launch' button, Appium will start like this

**Option 2 : Run Appium using node**

In order to use Appium with node, run  following commands in your terminal

    $ mkdir appium-test && cd appium-test
    $ npm install -g appium  # might have to do this with sudo
    $ sudo authorize_ios # enable developer use of iOS sim
    $ npm install wd
    $ appium &

OR you can clone appium repo

    $ git clone git://github.com/appium/appium.git
    $ cd appium 
    $ ./reset.sh --osx
    $ sudo `which grunt` authorize  OR $ sudo authorize_ios
    $ node server.js

###  Setting up Mobile App for Appium Tests

There are plenty of open-source mobile iPhone apps available here. I am using PlainNote App for this tutorial.  Let's create a project and setup our mobile app for Appium tests

    $ mkdir cucumber-appium
    $ cd cucumber-appium 
    $ git clone https://github.com/vkoser/PlainNote
    $ cd PlainNote

Now, you need to compile your app by running

    $ xcodebuild -sdk iphonesimulator6.0

This creates a " _build/Release-iphonesimulator_ " directory in your Xcode project that contains the " _PlainNote.app_ " package that you'll need to communicate with the Appium server.

    $ ls
    AppStoreIcon.png       MainWindow.xib         PlainNote_Prefix.pch   build
    Classes                NotesList.plist        README                 index.html
    Icon.png               PlainNote-Info.plist   RootViewController.xib main.m
    LICENSE                PlainNote.xcodeproj    Settings.bundle
    $ cd build/Release-iphonesimulator/
    $ ls
    PlainNote.app      PlainNote.app.dSYM

We need to setup this app with our Appium app. You can see the image above which shows that we have setup PlainNote  app with Appium

### Using Appium Inspector

Appium App on OSX is very handy to record and playback tests for your iOS app. You can launch 'Appium Inspector' by clicking on 'i' icon. Appium Inspector can find elements and perform actions on it. You can record and playback tests using Ruby, Python, Java, node etc etc.

**Watch this video Demo  **

Appium Inspector demo

### Setting up Cucumber and Appium

Let's create Cucumber project to run our iOS automated tests using Appium. We have already created 'cucumber-appium' directory above, we will set up cucumber project there. We need to make sure that, we are using _**ruby 1.9.3**_

    $ cd cucumber-appium
    $ rvm install 1.9.3
    $ rvm use 1.9.3

  * **Create Gemfile**

We need Gemfile in order to specify all our dependencies

    $ cd cucumber-appium
    $ vim Gemfile

Now insert following dependencies into the Gemfile

    source "https://www.rubygems.org"

    gem "rest-client"
    gem "rspec"
    gem "selenium-webdriver"
    gem "cucumber"
    gem "rspec-expectations"

Now we need to install bundle to download all dependencies

    $ bundle install

This will create 'Gemfile.lock' file.

  *   **Create Feature File  **

Now, we will write a feature file using Given When Then format. The feature file is written using Gherkin Domain Specific Language.

Let's create ' _features/plain_note.feature_ ' file.

    $ vim features/plain_note.feature

PlainNote app feature will look something like this

    Feature: Notes 
      As a iPhone user
      I want to PlainNote app
      So that I can make note of everything happening in my life

    Scenario: Add new note 
      Given I have App running with appium 
      When click + button 
      And I enter text "Data" and saved it 
      Then I should see "Data" note added on home page

This feature is self explanatory, we are going to add new note and make sure it displayed on Home page.

  * **Setup Cucumber Environment  **

Let's create ' _features/support/env.rb_ ' where we can put our support code.

    $ vim features/support/env.rb

Insert following code in the file.

    require 'rspec/expectations'
    require 'selenium-webdriver'

    APP_PATH = '/../../PlainNote/build/Release-iphonesimulator/PlainNote.app'

    def capabilities
      {
        'browserName' => 'iOS',
        'platform' => 'Mac',
        'version' => '6.0',
        'app' => absolute_app_path
      }
    end

    def absolute_app_path
      File.join(File.dirname(__FILE__), APP_PATH)
    end

    def server_url
      "http://127.0.0.1:4723/wd/hub"
    end

    def selenium
      @driver ||= Selenium::WebDriver.for(:remote, :desired_capabilities => capabilities, :url => server_url)
    end

    After { @driver.quit }

Now that, we have specified APP_PATH and defined server url where our Appium server is running. We have also created 'selenium' driver with all required desired capabilities. We will using 'selenium' object in our step_definition

  *   **Write Step definitions using Selenium-Webdriver  JSON Wire Protocol**

At this point if you run 'bundle exec cucumber' command it will tell you steps that are not implemented yet. We need to implement these step definitions using Selenium-Webdriver JSON Wire Protocol for Appium. Now , we will create step definition file and implement it

    $ vim features/step_definitions/plain_note.rb

Now add these step definitions to the file.

    Given(/^I have App running with appium$/) do
     # Make sure you have started appium server 
    end

    When(/^click \+ button$/) do
      selenium.find_element(:name, "Add").click
    end

    When(/^I enter text "(.*?)" and saved it$/) do |data|

    selenium.find_element(:xpath, "//window[1]/scrollview[1]/textview[1]").send_keys data
    selenium.find_element(:name, "Done").click
    selenium.find_element(:name, "Save").click
    end

    Then(/^I should see "(.*?)" note added on home page$/) do |text|
    note = selenium.find_element(:xpath,  "//window[1]/tableview[1]/cell[1]/text[1]")
    note.attribute("value").should match text 
    end

Now We are done with all steps now start appium server and run

    bundle exec cucumber features/plain_note.feature

You will see that application is launched with Xcode performing all the actions on Mobile app

You will see all the steps passed.

    $ bundle exec cucumber
    /Users/user/.rvm/gems/ruby-1.9.3-p392@global/gems/bundler-1.3.4/lib/bundler/runtime.rb:216: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    /Users/user/.rvm/gems/ruby-1.9.3-p392@global/gems/bundler-1.3.4/lib/bundler/runtime.rb:216: warning: Insecure world writable dir /Users/user in PATH, mode 040777
    Feature: Notes

      As a iPhone user
      I want to PlainNote app
      So that I can add make note of everything happening in my life

      Scenario: Add new note                             # features/plain_note.feature:7
        Given I have App running with appium             # features/step_definitions/plain_note.rb:2
        When click + button                              # features/step_definitions/plain_note.rb:6
        And I enter text "Data" and saved it             # features/step_definitions/plain_note.rb:10
        Then I should see "Data" note added on home page # features/step_definitions/plain_note.rb:17

    1 scenario (1 passed)
    4 steps (4 passed)
    0m32.385s

### Setting up Cucumber, Appium and SauceLabs

Saucelabs is a cloud testing framework which allow us to setup cross-browser, cross-platform and cross-device tests in the cloud. Saucelabs [@saucelabs] recently announced appium support which makes it easier to test Mobile apps in the cloud. You need to have saucelabs account in order to use it if not you can sign up for free account.

_Note: I have used my Saucelabs details for this tutorial, you can try with your own._

### App Setup for Sauce

In order to test PlainNote App on Saucelabs, we need to do some initial setup.

  * **Compile App for Sauce  **

In order to compile PlainNote App with sauce, we need to checkout an app to the different location.

    $ mkdir Test
    $ cd Test
    $ git clone https://github.com/vkoser/PlainNote
    $ cd PlainNote

Now we need to compile PlainNote App with sauce. [ Note Additional parameter TARGET_DEVICE_FAMILY]

    xcodebuild -sdk iphonesimulator6.0 TARGETED_DEVICE_FAMILY=1

In Sauce, TARGETED_DEVICE_FAMILY parameter had different values e.g 1 is for iPhone, 2 is for iPad and 1,2 is for universal apps.

Now, once build is successful, it will create " _PlaneNote.app_ " at ' _/build/Release-iphonesimulator_ '.

    $ cd /build/Release-iphonesimulator/
    $ ls
    PlainNote.app PlainNote.app.dSYM

  *   **Zip the PlainNote App & Upload to SauceLabs **

    $ zip -r PlainNote.zip PlainNote.app
     adding: PlainNote.app/ (stored 0%)
     adding: PlainNote.app/DetailNoteViewControler.nib (deflated 38%)
     adding: PlainNote.app/Icon.png (stored 0%)
     adding: PlainNote.app/index.html (deflated 65%)
     adding: PlainNote.app/Info.plist (deflated 28%)
     adding: PlainNote.app/MainWindow.nib (deflated 41%)
     adding: PlainNote.app/NotesList.plist (deflated 27%)
     adding: PlainNote.app/PkgInfo (stored 0%)
     adding: PlainNote.app/PlainNote (deflated 69%)
     adding: PlainNote.app/RootViewController.nib (deflated 36%)
     adding: PlainNote.app/Settings.bundle/ (stored 0%)
     adding: PlainNote.app/Settings.bundle/en.lproj/ (stored 0%)
     adding: PlainNote.app/Settings.bundle/en.lproj/Root.strings (deflated 63%)
     adding: PlainNote.app/Settings.bundle/Root.plist (deflated 82%)
     adding: PlainNote.app/WebViewController.nib (deflated 34%)

Now you will see ' _PlainNote.zip_ ' file in that directory

    $ ls
    PlainNote.app      PlainNote.app.dSYM PlainNote.zip

Now, we need to upload this file to Sauce Labs temporary stoarage using Sauce REST API

    $ curl -u Shashikant86:a0e37e25-e2f3-4cba-95d3-936007d8bfc3 -X POST "http://saucelabs.com/rest/v1/storage/Shashikant86/PlainNote.zip?overwrite=true" -H "Content-Type: application/octet-stream" --data-binary @/path/to/PlainNote/build/Release-iphonesimulator/PlainNote.zip

It will show you response

    {"username": "Shashikant86", "size": 42190, "md5": "6ef42125b024188976af9d6b8a104105", "filename": "PlainNote.zip"}

It will be now uploaded to " _ **sauce-storage:PlainNote.zip**_ ". This will look like :

_**Note: I have  committed "PlainNote.zip" file to GitHub , so that you can use it directly to upload it to SauceLabs.**_

Now, our App is ready to use it on SauceLabs

### Cucumber- SauceLabs-Appium Setup

In Order to setup mobile APP on the Sauce Labs,  we need to define 'profile' in the ' _featues/support/env.rb_ ' file

    $ vim features/support/env.rb

  * Add Sauce Capabilities and Sauce Url

We need to add sauce_capabilities mentioned in the saucelabs appium tutorial. We also need to specify sauce-url where the tests will be running. It would be saucelabs  url ' _http://Shashikant86:a0e37e25-e2f3-4cba-95d3-936007d8bfc3@ondemand.saucelabs.com:80/wd/hub'_

    def sauce_capabilities
      {

        'app' => 'sauce-storage:PlainNote.zip',
        'device' => 'iPhone Simulator',
        'username' => 'Shashikant86',
        'access-key' => 'a0e37e25-e2f3-4cba-95d3-936007d8bfc3',
        #'os' => 'iOS'
        #'browserName' => 'iPhone',
        'platform' => 'OS X 10.8',
        'version' => '6.0',
        'name' => 'Running PlainNote wit Cucumber and Appium', 
        'passed' => 'true'

      }

    def sauce_url "http://Shashikant86:a0e37e25-e2f3-4cba-95d3-936007d8bfc3@ondemand.saucelabs.com:80/wd/hub" end

  *   **Add Driver for Sauce**

    def sauce
      @sauce ||= Selenium::WebDriver.for(:remote, :desired_capabilities => sauce_capabilities, :url => sauce_url)
    end
    After { @sauce.quit }

You can see in the source code that, we have new feature file ' _features/plain_note_sauce.feature'  _implemented in the same way but using sauce driver object in the _'feature/step_definitions/plain_note_sauce.rb'  _

Now you can run sauce feature file

    $  bundle exec cucumber features/plain_note_sauce.feature

and you will see Tests running on the SauceLabs. Once everything done.

You can watch video and screenshots of what happened on SauceLabs over  here

### Source-Code

The source-code of the demo is available on GitHub Cucumber-Appium. You can try it yourself.

    $ git clone https://github.com/Shashikant86/cucumber-appium
    $ cd cucumber-appium
    $ rvm use 1.9.3
    $ bundle install

To run with local profile, start Appium and

    bundle exec cucumber features/plain_note.feature

To run against Sauce, you need to upload App  to sauce using your sauce details also change usename and api key in the ' _features/support/env.rb_ ' with you details

    curl -u USERNAME:API-KEY -X POST "http://saucelabs.com/rest/v1/storage/USERNAME/PlainNote.zip?overwrite=true" -H "Content-Type: application/octet-stream" --data-binary @/path/to/cucumber-appium/PlainNote.zip

Then you can run sauce feature with Appium.

    bundle exec cucumber features/plain_note_sauce.feature

Mobile testing framework Appium can be used for iOS automation with BDD tool like Cucumber and cloud testing services SauceLabs. Happy BDD !

## Testing Vim iOS Mobile App with Cucumber & Calabash

### Mobile Test Automation

Mobile testing is a real challenge when it comes to automation because of variety of the platforms, versions and interfaces. Let's say, iOS Apps, We got iPhones, iPads and different versions of them. Android devices are even more complex. Mobile test automation is a emerging topic in recent days and selecting automation libraries takes lot of research and investigation of the variety of test automation tools. In this tutorial, I will explain how I set up Calabash, Cucumber test automation framework on Mac OSX to test Vim iOS application.

### Calabash: Mobile Test Automation Library

Calabash is a mobile test automation technology which currently supports iOS and Android Apps. Calabash is maintained by company called 'LessPainful'. Github repositories are maintained by Karl Krukow [@karlkrukow].

I got introduced with Calabash while attending Tech Talk by Moncef Belyamani at AOL. He has worked on various AOL mobile apps automation by using combination of  Calabash and Cucumber. Watch his talk at Mobile Testing Summit last year on 'Calabash: Tips and Tricks'. By reading his blog post 'iOS Automated Testing with Calabash, Cucumber and Ruby', I have decided to dive directly in to Calabash without spending time on evaluating other tools. Calabash seems like awesome option for mobile test automation.

Calabash currently support Cucumber which is BDD tool for the Ruby application. We look forward Calabash support for Behat as well in the near future.

### Vim iOS Application

There are number of open-source iOS Apps available here but I have selected Vim iOS application. It's because Vim is different than other application because of it's interface and usage. It doesn't have Buttons, Fields, Placeholders or links. I thought, it would be challenging to test text editor like Vim on mobile devices.

You can find source code on GitHub here. You need to setup Vim app as a Xcode project. It's simple, from your Xcode, Goto File->Open->Vim[your_project].

### Get Started with Calabash

I asume that, you have already setup development environment on your Mac by using Moncef's blog. Basically, you need to install following tools and services.

  * Xcode with Command line Tools 
  * Various versions iOS Simulators. [ It comes with Xcode]
  * Homebrew [Package Management ]
  * Git
  * RVM and Ruby gems
  * Cucumber

I have already setup all these things on my Mac OSX. Again I would strongly recommend Moncef's blog to do this.

### Download Vim iOS Source-Code

Once you done with all the necessary setup, you need source code for your application. You can clone Github repository directly into your Mac

    $ git clone https://github.com/applidium/Vim

Now, it would be an awesome idea to separate RVM for Calabash project from other Ruby application.

    $ cd Vim/
    $ rvm --rvmrc --create use 1.9.3@calabash

### Install Calabash-Cucumber

Now, It's time to install Calabash-Cucumber gems into our Vim directory & setup Calabash framework. You need to run following commands in sequence

    $ gem install calabash-cucumber
    $ calabash-ios setup
    $ calabash-ios gen

These commands will setup Calabash Framework and create sample Cucumber feature file into your project. Here is screenshot.

We need to hit return after this step to continue installation.

### Setup Xcode

You can setup Xcode project manually by following step by step instructions on Moncef's blog but I think, you can still use 'Fast Track' which will do most of the setup thing automatically and then you can perform checks if setup is right or wrong.

In order to do that, you need to run 'cucumber' command which will fail complaining about Xcode setup but it will perform most of the task mentioned in the 'Manual Setup'

    $cucumber

Now, here are some important checks, you need to perform on Xcode in order to confirm status of your Xcode setup

### Ensure Scheme [-cal]

First thing, you need to ensure that, new scheme is automatically generated. This duplicated project is called 'Vim-cal'. You will see screen something like this:

### Check Build Setting: Product Name

In your Xcode, Go to Build Settings and Search for " Product name". Make sure result id 'Vim-cal'

###  Check Calabash Framework in the App

You can simply 'ls' into your project and see if 'Calabash-Framework' directory is available.

    Shashi-MacBook-Pro:Vim user$ ls
    Contents               README_bindos.txt      Users                  runtime
    Contents.info          README_dos.txt         Vim.info               runtime.info
    Filelist               README_extra.txt       Vim.xcodeproj          
    Makefile               README_mac.txt         Xxd.info      
    README.txt             README_ole.txt         calabash.framework      src
    README.txt.info        README_os2.txt         configure              src.info
    README_ami.txt         README_os390.txt       csdpmi4b.zip           uninstal.txt
    README_ami.txt.info    README_src.txt         farsi                  vimdir.info
    README_amibin.txt      README_srcdos.txt      features               vimtutor.bat
    README_amibin.txt.info README_unix.txt        libs                   vimtutor.com
    README_amisrc.txt      README_vms.txt         nsis
    README_amisrc.txt.info README_w32s.txt        pixmaps

### Ensure Link Binary with CFNetwork.framework.

Go to 'Build Phase' and expand 'Link Binary with Libraries' You have to make sure you got ' CFNetwork.framework' library.

###  Ensure Other Linker Flag

Go to 'Build Seting' and Search for ' Other Linker'. You should see flag is pointing to 'Calabash framework'

### Ensure Accessibility Turned ON.

In order to perform some functions on iOS app you need to turn, Accessibility ON feature ON. In order to do that, you need to RUN Vim-Cal App. Once emulator is launched, Check the 'Output' by clicking on the 'View' in the top right corner.

Go to 'Settings->General->Accessibility" and toggle ' Accessibility Inspector 'ON'. You will see something like this.

### Calabash-Cucumber

Now that, we have done with all the setup. It's time to execute Cucumber to see the auto generated feature is passed.

    $cucumber

Now, you will see auto generated feature is passed and screenshot is saved in the project directory.

### Add Another Feature

Now , we will add another feature into out Vim project.

    $ sudo vim visual_mode.feature
    Feature: Test visual mode of the Vim editor
      In order to use Vim 
      As a Vim user
      I want to enter on the visual mode

    Scenario: Test visual mode 
        Given I am on the Welcome Screen
        When I swipe left
        And I wait for 2.3 seconds
        Then I don't see the "VIM - Vi IMproved"

This feature is using predefined Calabash Steps so that we don't need to write implementation code. Now we will run Cucumber to see all steps passed. Watch the video demo below.

### What Next?

In this post, we have seen testing look and feel of Vim using predefined Calabash Steps. In the future post, we will see

  * Using Calabash Custom Steps & Ruby Api's to test Vim iOS app 
  * Testing all features of the Vim like insert mode, copy, syntax etc etc.

I know, it will be challenge, you can join me to contribute to this project. Please feel free to fork Github and Contribute.

**GitHub :Calabash-Cucumber-Vim**

Calabash is a awesome automation framework for testing iOS and Android apps by using Cucumber. Calabash helps QA, Developers to write robust automated test suits to test mobile App. Again, we look forward, Calabash support for the Behat.

**Happy Mobile Testing !!**

## Setting up Vagrantified Android Appium environment provisioned with Ansible

### Vagrant

Vagrant is a great tool to build and distribute development environments. Vagrant allows us to keep development environment configuration same on various machines in order to avoid issues like "It works on my machine !". If you haven't started with vagrant please go though the getting started guide of vagrant. It's very easy to setup. I have written up a post with detailed screenshots here

### Ansible: Vagrant Provisioner

Vagrant can be provisioned with various provisioners. We can use basic shell provisioner or Chef or Puppet to provision vagrant boxes. My choice is Ansible ,  there are many reasons to choose Ansible but here are few

  * Ansible is very simple to configure
  * Ansible has many simple and easy  playbooks
  * Ansible has predefined roles which we can use directly. It reduces lots of scripting.
  * Ansible is cross platform
  * Ansible output is very readable as compared to Shell and Chef.

### Android Appium with Ruby

Now that, we will provision Appium Android and Ruby environment with Ansible on a vagrant box. Appium is a mobile test automation framework. In order to set it up, we need following technology stack

  * Ansible
  * Ruby and RVM
  * NodeJS
  * Android SDK
  * Java

### **Install Ansible  **

On Mac OSX, you can install Ansible with Brew

    $ brew install ansible

### Create Vagrantfile

Let's create a project directory and Vagrantfile inside the project

    $ mkdir vagrant-appium-ansible

    $ cd vagrant-appium-ansible

    $ vim Vagrantfile

Add details to  Vagrantfile which looks like this:

    # -*- mode: ruby -*-
    # vi: set ft=ruby :
    # Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
    VAGRANTFILE_API_VERSION = "2"
    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

      config.vm.box = "ubuntu/trusty64"
      config.vm.hostname = "appium-ansible"

      config.vm.provider "virtualbox" do |vb|
              vb.customize ['modifyvm', :id, '--usb', 'on']
        vb.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/vagrant", "1"]
        vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'Galaxy Nexus', '--vendorid', '0x04e8']
      end

        config.vm.provision :ansible do |ansible|
        ansible.playbook = "playbook.yml"
     end
    end

Vagrantfile:

Now Let's understand what's in the vagrant file.

  * ### **Box Specification**

We have specifiled box name as 'ubuntu/trusty64′ which is a ubuntu desktop 14.04 also we have provided host name as 'appium-ansible'

  * **USB  and Vagrant Box**

Second part is all about USB connection with Vagrant Box. We need to specify vendorID and ProductID of the attached device in order to recognise the device by the box.

  * ### **Provisioning  **

In the final part of the Vagrantfile, we have specified config file 'playbook.yml' for ansible.

###  Create playbook.yml

Ansible uses 'playbook.yml' file to provision vagrant box. This file has all the task, to know more please read ansible playbook. You can find our project 'playbook.yml' on GitHub here.

  * ### **Install Required packages**

Now we will configure all required debian packages for ruby, appium and nodejs

  * ### **Install Android and RVM**

This part of the playbook file install Android SDK and Ruby/RVM.

###  android.rules

We also need out android.rules file which will be then copied to '/etc/udev/rule.d/51-android.rules'  
Sample file can be found on GitHub here

### Vagrant UP

Now that, we are all set to boot our vagrant machine. We can now run command

    $ vagrant up

This will boot new ubuntu box with specified host name.

Now, our machine is booted and ready. It will now start provisioning from our playbook.

### Vagrant Provision

Now that our machine will first install all the required packaged and then carry on installing RVM and Ruby

Ansible will then install Android and Appium as follows

### Vagrant SSH

Now that we have our ubuntu machine fully provisioned with Ansible tasks. Now lets ssh into the machine and check all the things installed correctly

We can see that Android SDK and RVM and NodeJS has been installed correctly.

### Run Appium Server

Now that, we have 'node_modules' directory with appium installed. We can launch appium server like this

    $ nodejs node_modules/appium/bin/appium.js

We can now make use of the Appium server to launch our mobile automated scenarios.

#

We can build and distribute vagrant development environments fully provisioned with Ansible for Appium mobile test automation.  This can save lot of time in settting up development environments on every machine.

### Source Code

You can find source code on GitHub 'vagrant-ansible-appium'

**Setting up Vagrant development environment for Android Appium provisioned with Ansible**  
<https://github.com/Shashikant86/vagrant-ansible-appium>  
0 forks.  
0 open issues.  
Recent commits:

  * Development environment Vagrant Appium and Ansible, Shashikant86

#### Watch it on Youtube

Vagrant-Ansible-Appium

# Continuous Integration Setup

## Adventures with Jenkins CI on Mac OSX & Linux

In an agile software development, Continuous integration became integral part of agile process and agile team won't be considered as effective without effective and visible continuous integration(CI). Continuous integration server runs automated test after each time developers check-in into the source code repository and notify team in case build failed. Continuous integration won't allow developers to build legacy code which in turn increase technical debt. Continuous integration helps a lot in quality of the product.

### **Jenkins:**

Jenkins is a most popular continuous integration tool. Jenkins has been developed and maintained by Kohsuke Kawaguchi who is currently working at cloudbees. Jenkins became so powerful CI server due to it's nice looking web interface and it's hundred's of plugins.

In this short tutorial, we will learn how to install jenkins on your computer.

### **Jenkins On Mac OSX:**

  * ### Using Jenkins-OSX installer package

Simplest way of installing Jenkins on Mac OSX is to download 0sx-installer package () from Jenkins websiteand following the instructions. You can find this package in your 'Downloads' directory called ' jenkins-{version}.pkg'. Now current version is 'jenkins-1.478.pkg' .

Double click on the package, you will get installer window and follow the steps which includes Introduction, License, Destination Select (location of Jenkins), Installtion Type, Installtion and Summary. Add jenkins package in your Applications and you are done! So simple isn't it?

Remember, this package is broken and you may get get a 404 'not found' message from the winstone-server that is bundled. If you dig in your syslog, you'll find a reviling stack trace that indicates that a file can't be found.  
Solution for this issue is to create dedicated users to run jenkins. Run following commands from your terminal

    sudo dscl . create /Users/jenkins
    sudo dscl . create /Users/jenkins PrimaryGroupID 1
    sudo dscl . create /Users/jenkins UniqueID 300
    sudo dscl . create /Users/jenkins UserShell /bin/bash
    sudo dscl . create /Users/jenkins home /Users/Shared/Jenkins/Home/
    sudo dscl . create /Users/jenkins NFSHomeDirectory /Users/Shared/Jenkins/Home/
    sudo dscl . passwd /Users/jenkins

Then update at /Library/LaunchDaemons/org.jenkins-ci.plist file to use 'jenkins' user`  
UserName  
jenkins  
`

After doing that, the Home folder of jenkins, /Users/Shared/Jenkins/Home needs a new owner.

    sudo chown -R jenkins /Users/Shared/Jenkins

Finally, unload and reload jenkins service

    sudo launchctl unload -w /Library/LaunchDaemons/org.jenkins-ci.plist
    sudo launchctl load -w /Library/LaunchDaemons/org.jenkins-ci.plist

If you need to access your git repos using a public ssh key, you can generate one now by logging in as the jenkins user and running ssh-keygen

    Shashi-MacBook-Pro:~ user$ sudo -su jenkins
    bash-3.2$ ssh-keygen
    Generating public/private rsa key pair.
    Enter file in which to save the key (/Users/Shared/Jenkins/Home//.ssh/id_rsa):
    Created directory '/Users/Shared/Jenkins/Home//.ssh'.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /Users/Shared/Jenkins/Home//.ssh/id_rsa.
    Your public key has been saved in /Users/Shared/Jenkins/Home//.ssh/id_rsa.pub.
    The key fingerprint is:
    42:74:b0:02:e1:09:77:32:38:c4:34:fa:d6:9c:7f:6a _jenkins@Shashi-MacBook-Pro.local
    The key's randomart image is:
    +--[ RSA 2048]----+
    |==*.. o.. |
    |+=.* . o |
    |..o . o |
    | . o + |
    | o + . S |
    | . . . |
    | . . |
    | Eo |
    | .. |
    +-----------------+

Now, open your web browser and type ' http://localhost:8080/' and see jenkins installed in your Mac.

  * ### Downloading War file (standalone)

You can also install jenkins as a standalone application by downloading jenkins.war file from jenkinswebsite. On right hand side of the website, you will find 'Download Jenkins' and Java Web Archive (.war). Download the latest version. It will be downloaded in your 'Downloads' directory. Now open terminal and run these commands (in this case 'Shashi-MacBook-Pro:Downloads user$' is my home directory.

    Shashi-MacBook-Pro:~ user$ cd ~/Downloads
    Shashi-MacBook-Pro:Downloads user$ java -jar jenkins.war<code> 
    </code>

Now, open your web browser and type ' http://localhost:8080/' and see jenkins installed in your Mac.

  * ### Using Mac Brew package to install Jenkins  (Prefred )

I pearsonally, prefer this method of installing Jenkins on Mac as It will many problems that you may face if you install Jenkins using any of the above method.

You can't clone private github repositories and you can't use your own private key if you install Jenkins with above method. So I would definately recommend this method in order to instal Jenkins o Mac. Pre-requisite is You must have homebrew installed on your Mac.

I assume that, you got homebrew installed on local Mac. Now try running these commands`  
`

    Shashi-MacBook-Pro:~ user$ brew install jenkins
    Warning: Your Xcode (4.3.3) is outdated
    Please install Xcode 4.4.1.
    ==> Downloading http://mirrors.jenkins-ci.org/war/1.477/jenkins.war
    ######################################################################## 100.0%
    ==> Caveats
    If this is your first install, automatically load on login with:
    mkdir -p ~/Library/LaunchAgents
    cp /usr/local/Cellar/jenkins/1.477/homebrew.mxcl.jenkins.plist ~/Library/LaunchAgents/
    launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.jenkins.plist
    If this is an upgrade and you already have the homebrew.mxcl.jenkins.plist loaded:
    launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.jenkins.plist
    cp /usr/local/Cellar/jenkins/1.477/homebrew.mxcl.jenkins.plist ~/Library/LaunchAgents/
    launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.jenkins.plist

Or start it manually:

    java -jar /usr/local/Cellar/jenkins/1.477/libexec/jenkins.war

==> Summary  
/usr/local/Cellar/jenkins/1.477: 3 files, 47M, built in 18 seconds

Now run following commands in order to create Jenkins user and deamon`  
`

    sudo mkdir /var/jenkins
    sudo /usr/sbin/dseditgroup -o create -r 'Jenkins CI Group' -i 600 _jenkins
    sudo dscl . -append /Groups/_jenkins passwd "*"
    sudo dscl . -create /Users/_jenkins
    sudo dscl . -append /Users/_jenkins RecordName jenkins
    sudo dscl . -append /Users/_jenkins RealName "Jenkins CI Server"
    sudo dscl . -append /Users/_jenkins uid 600
    sudo dscl . -append /Users/_jenkins gid 600
    sudo dscl . -append /Users/_jenkins shell /usr/bin/false
    sudo dscl . -append /Users/_jenkins home /var/jenkins
    sudo dscl . -append /Users/_jenkins passwd "*"
    sudo dscl . -append /Groups/_jenkins GroupMembership _jenkins
    sudo chown -R jenkins /var/jenkins

Mac OS uses launchd to control daemons and agents. It's pretty easy to create a launch daemon. Create the file `/Library/LaunchDaemons/org.jenkins-ci.plist` with the following content, based on the plist from the homebrew jenkins formula. You may need to update the version number in the ProgramArguments.

    Shashi-MacBook-Pro:~ user$ sudo touch /Library/LaunchDaemons/org.jenkins-ci.plist<code></code>

Insert following containt into this file. You may need to change the version of jenkins accordingly.`  
`

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Label</key>
    <string>Jenkins</string>
    <key>ProgramArguments</key>
    <array>
    <string>/usr/bin/java</string>
    <string>-jar</string>
    <string>/usr/local/Cellar/jenkins/1.414/lib/jenkins.war</string>
    </array>
    <key>OnDemand</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>UserName</key>
    <string>jenkins</string>
    </dict>
    </plist>

Now you need to load the daemon using

    sudo launchctl unload -w /Library/LaunchDaemons/org.jenkins-ci.plist
    sudo launchctl load -w /Library/LaunchDaemons/org.jenkins-ci.plist<code></code>

Or You can just rebot your Mac.

Create an ssh key

Like I said, I wanted jenkins to have its own ssh identity. This is fairly easy:`  
`

    sudo -u jenkins ssh-keygen

You will see output like this

    Shashi-MacBook-Pro:~ user$ sudo -u jenkins ssh-keygen
    Password:
    Generating public/private rsa key pair.
    Enter file in which to save the key (/var/jenkins/.ssh/id_rsa):
    Created directory '/var/jenkins/.ssh'.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /var/jenkins/.ssh/id_rsa.
    Your public key has been saved in /var/jenkins/.ssh/id_rsa.pub.
    The key fingerprint is:
    fa:e9:2f:fa:89:f3:2a:60:d3:da:06:94:b5:63:9b:f7 _jenkins@Shashi-MacBook-Pro.local
    The key's randomart image is:
    +--[ RSA 2048]----+
    | |
    | . |
    | o . |
    | o + |
    | . o + S |
    | = + .. |
    | . * ... |
    | . + .oEo |
    | . .+BBo. |
    +-----------------+

The new key is in /var/jenkins/.ssh/id_rsa.pub and can be copied to github, or wherever you have your source code.

### **Jenkins on Ubuntu**

Setting up Jenkins on ubuntu is fairly simple. You need to run following commands in order to achieve this

    wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
    sudo sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
    sudo aptitude update
    sudo aptitude install jenkins

To update Jenkins run

    sudo aptitude update
    sudo aptitude install jenkins

### **Jenkins on CentOS**

CentOS has yum package for Jenkins. Just run as a root user.`  
`

    yum install jenkins

Now, open your web browser and type ' http://ipaddress:8080/' and see jenkins installed.

Enjoy this installed interface of Jenkins. In the next tutorial, we will see how to create job in Jenkins.

Happy CI !!

## [Re]-Installing Jenkins on OSX Mavericks

### Jenkins Installation

Jenkins is the best Continuous integration tool in the Market. Jenkins is so popular because of hundreds of plug-ins that user can use to configure Job.

Hope you have upgraded your OSX to Mavericks and lost your existing Jenkins installation. I have written blog post few months back about 'Installing Jenkins on Mac OSX', at that time it was OSX Mountain Lion.

### Jenkins on OSX- Mavericks

Download Jenkins Package for Mac OSX from Jenkins official website. If you try to install package and got this error.

You need to tweak security settings in your Mac OSX. Go to Preferences-> Security & Privacy and 'Allow apps downloaded from; to **anywhere**

Now, you can download and install Jenkins. Once you followed all the instructions on your screen you can see Jenkins has been installed successfully. It would launch Jenkins automatically OR You can visit http://localhost:8080 and see Jenkins Home Page.

I got few Jenkins job from the original installations so they are appearing there.

### Java & Mavericks

On OSX Mavericks, you will find that you have lost Java installation. You may need to install Java, follow this blog from OSX Daily [@osxdaily] called 'Install Java on OSX-Mavericks'

### Get Nice Jenkins Plugins

There are wide range of Jenkins Plugins available there, just go to 'Manage Jenkins' -> 'Manage Plug-ins'. You will see list of plug-ins available there, I have installed few useful plug-ins like Cucumber, Violation and so on

### Starting and Stoping Jenkins

Jenkins has been now start or stop Jenkins from command line :

STOP :

    $ sudo launchctl unload -w /Library/LaunchAgents/org.jenkins-ci.plist

START :

    sudo launchctl load -w /Library/LaunchAgents/org.jenkins-ci.plist

Have fun with Continuous Integration.

## Launching Jenkins Slaves on the fly.

### Jenkins Master-Slave Architecture

Jenkins is a awesome Continuous Integration tool which allow you to add multiple slaves as per your project requirement . Working in the distributed environment, we need different machine for different purpose. We might need Ubuntu machines to do specific tasks, CentOS machines to perform additional task and so on.

While thinking Continuous Integration in cross-browser and cross-platform environment, you must have master slave architecture of Jenkins. You have master mode and millions of slaves running under it (not millions though :)). You can read more about adding multiple slaves here.

Let's say your master node is running on http://master-yourawesomedomain: 8080

Next step is to add few machines as a slave in the same data center. You must have to make sure that your master can ssh into slave machine.

Try this

    <span class="GRcorrect">ssh</span> user@master-yourawesomedomain.com

Now you are logged into Master node

Tyr ssh into slave machine eg we have 2 slaves

1] slave-01.yourawesomedomain.com

2] slave-02.yourawesomedomain.com

    you@master-yourawesomedomain$ ssh user@slave-01.yourawesomedomain.com

You should add your private key to known host and you will be able to access slave machine.

Let's see how you can do from Jenkins Master interface.

###  Add Node

Login to your Master Jenkins http://master-yourawesomedomain: 8080 with your Username and Password.

Click on 'Manage Jenkins' → Manage Nodes

You will see a screen something like this:

Now Click on 'New Node' and fill in the details like this :

###  Configure Node

Next thing is you have to configure your slave as per your requirement.

Few things to note:

  * # of executor: You shouls put it to 1 or 2
  * Remote FS root : Better to have jenkins directory as /var/jenkins
  * Host : This must be a ip address of your slave machine
  * Username : you must run all your tests as a jenkins_user
  * Password : you can use password but I would prefer private key. It's upto you and your companies security policy.Once you happy save the config.

You will see window to launch new slave like this:

### Launch Node

Click on the Launch Slave and You have new machine to run your tests. !

All Done. You got new slave to run tests on Jenkins.

Happy CI !!

# CUCUMBER BDD TIMES

### Cucumber BDD Times: Weekly NewsPaper

### Cucumber BDD Times

Hello BDD folks, Behaviour Driven Development is awesome and Cucumber is one popular tool to make BDD work.

You really can't afford to lag behind in the world of BDD and Cucumber. Good News is, we have weekly newspaper called "Cucumber BDD Times".

Cucumber BDD times has all the latest news, trends, discussions, tools, and jobs as it's content. Here is how it look like.

There is no point waiting otherwise you will miss very important content. Get on and Subscribe here

### Contribute to Paper

It's very easy to get your content published on Cucumber BDD Time. You just need to do following

  * Tweet you content with #Cucumber or #BDD hashtag
  * Tweet your work with 'Cucumber BDD' text in it.
  * Google plus your Content with text ' Cucumber BDD'
  * Post on Facebook with hash tag #BDD #Cucumber or text 'Cucumber BDD'

**Let's contribute and share our work to entire BDD world !**

# References

### Links to demo

**Personal Website**

_https://shashikantjagtap.net_

**GitHub  **  
_https://github.com/Shashikant86_

**Youtube**

_https://www.youtube.com/user/BehatPHP/videos_
