Archive for the ‘ruby’ Category

Cucumber: Passing Test Data as Table from Scenario

January 20, 2016 Leave a comment

While we can pass test data as table from the feature file through Scenario Outline:

Scenario Outline: User updates user information
 Given I login to application
 And I go to user profile page
 And I enter "<gender>" into field of "gender_element";
 And I enter "<age>" into field of "age_element";
 And I enter "<location>" into field of "location_element";
 Then I verify user updates are saved
 | gender | age | location |
 | Female | 20 | Singapore |

Here’s another option to pass your data in table format through your step definition.

Scenario: User updates user information
 Given I login to application
 And I go to user profile page
 When I update user information with options:
  | Gender | Female |
  | Age | 20 |
  | Location | Singapore |
 Then I verify user updates are saved

#Step Definitions File

#step definition to populate textfields
Then /^I enter "(.*)" into field of "(.*)"$/ do |value, field|
 textfield(I18n.translate!(field)).send_keys value

#step definition that accepts test data from the feature file as table
When /^I update user information(?: with options:)?$/ do |table|

 options = table.rows_hash
 step %Q[I enter "#{options['Gender']}" into field of "gender_element"]
 step %Q[I enter "#{options['Age']}" into field of "age_element"]
 step %Q[I enter "#{options['Location']}" into field of "location_element"]
 step %Q[I press button labelled "bt_address_suggestion_use_this"] 

#step definition that accepts test data from the feature file as table with default value
When /^I update user information(?: with options:)?$/ do |table|
 default_value = {
 'Age' = "18",
 'Location' = "United States"
 options = default_value.merge(table.rows_hash)
 step %Q[I enter "#{options['Gender']}" into field of "gender_element"]
 step %Q[I enter "#{options['Age']}" into field of "age_element"]
 step %Q[I enter "#{options['Location']}" into field of "location_element"]
 step %Q[I press button labelled "bt_address_suggestion_use_this"]
Categories: cucumber, ruby, selenium

Cucumber: Using JSON Parser

February 25, 2015 Leave a comment

JavaScript Object Notation(JSON) is a lightweight data-interchange format useful to generate and parse data

Sample Data:

{‘user’:{‘FirstName’:’User1′, ‘LastName’:’Sample’, ‘Gender’:’Female’, ‘BirthDate’:’01/01/1990′}}

Suppose we are to use the above user data, parse it into an hash and use the array hash as input to a sign up screen.

Here’s a snippet of how to use JSON in this particular scenario

require “json”

my_data = "{'user':{'FirstName':'User', 'LastName':'Sample', 'Gender':'Female', 'BirthDate':'01/01/1990'}}"

##method to parse user data

def getNewUserData

@new_user = JSON.parse my_data


:firstName => new_user['user']['FirstName'],

:lastName => new_user['user']['LastName'],

:gender => new_user['user']['Gender'],

:birthDate => new_user['user']['BirthDate']



##method to populate the sign up screen

def fillOutSignUpScreen

step %Q[I enter "#{@new_user[:firstName]}" to the "signup.firstname"]

step %Q[I enter "#{@new_user[:lastName]}" to the "signup.lastname"]

step %Q[I enter "#{@new_user[:gender]}" to the "signup.gender"]

step %Q[I enter "#{@new_user[:birthDate]}" to the "signup.birthdate"]


For more functions and complete library you may refer to

Categories: ruby Tags: ,

Cucumber: Verify page content from a data source

July 21, 2014 1 comment

One good practice in “Cuking” is to not crowd your feature files with all the text validations. In this post I’ll be sharing how you can use an external data source to be compared with the actual UI page for content validation purposes.

First prepare your textfile by inputting all the expected content in the page you want to assert. Save this in a your desired location which later on you’ll need to specify in your step definition.

Step Definition

And /^I verify ([^"]*) page content$/ do |page|
 case page
   when 'Terms and Conditions'
     $file = File.expand_path(File.dirname(__FILE__) + '/{location of your file}/terms_and_conditions.txt')
   #you can add other pages to validate within the case
 $content =$file)
 $content.readlines.each do |line|
   puts "#{line}"
   page.text.should have_content("#{line}")

In your feature file assuming all the other step definitions are in place, you’ll just need to call your ‘I verify ([^”]*) page content’ step with the page variable in our example ‘Terms and Conditions’

Scenario: User verify contents of Home page
  Given User go to Terms and Conditions page
  And I verify Terms and Conditions page content

In other cases that you nedd to save your text validations in a csv data source, for example maintaining a csv file with all the expected labels per page:


Your step definition should look something like this:

And /^I verify fields from "([^"]*)"$/ do |page|
  $source = "/{location of your file}/fields.csv"
  FasterCSV.foreach(File.expand_path(File.dirname(__FILE__) + "#{$source}"), :headers => true) do |row|
      if row.header?("#{page}")
        if row["#{page"] != nil
          puts row["#{page}"]
          $field = row["#{page}"]
          page.text.should match(/#{$field}/)
    rescue => e
      raise e

Then in your feature file, you just call the step definition with the csv’s column header as a parameter:

Scenario: User verify contents of Home page
  Given User go to Login page
   Then I verify fields from "Login Page"
   And User go to Registration Page
   Then I verify fields from "Registration Page"

Cucumber: Read from File

November 1, 2012 1 comment

As your automated testing mature, you don’t want to limit users hard coding their application under test or browser driver all in the ENVironment file(env.rb). You can customized your environment by creating a configuration file where you can define variables like applications URL, timeout, database configurations and the like.

From the basic folder structure discussed in Automated Testing with Cucumber + Capybara post, add two more files:

config > environments.yml
support > custom_config.rb

environments.yml – contains all the environment variables that you can use



custom_config.rb – ruby code where you configure your code to read from a specific file

require "erb"

module CustomConfig
 unless defined? @@env_config
 puts "loading environments.yml..."
 env = (ENV['ENVIRONMENT'] && ENV['ENVIRONMENT'].to_sym) || :google
 environments = YAML.load('../../../config/environments.yml', __FILE__))).result)
 @@env_config = environments[env.to_s]
 raise "No config found for environment: #{env}" unless @@env_config

def env_config



Your base folder should look like these by now:

Revised Base Folder

Then edit your env.rb by adding the following lines to your environment file.

require File.expand_path(‘../custom_config’, __FILE__)
include CustomConfig

Also update Capybara.app_host definition to look up to @@env_config. Your env.rb file should be edited to something like this:


require 'capybara'
require 'capybara/cucumber'
require File.expand_path('../custom_config', __FILE__)
include CustomConfig

Capybara.default_driver = :selenium
Capybara.app_host = env_config['app_host']
Capybara.default_wait_time = 20


Notice in line #07 of your env.rb you are basically pointing app host to whatever environment you set in your custom_config.rbenv variable, (see line #06) for this example :google

From here on you should still be able to run your simple_search.feature file without error, the only difference is your code reads now from a specific file – environments.yml, through custom_config.rb.

Automated Testing with Cucumber + Capybara

October 29, 2012 10 comments

In this post we will introduce another gem called Capybara.

Capybara is an acceptance testing framework with a higher level API and support for multiple backends, supports Selenium and runs in different browsers.

Others may ask, “Why would I use capybara if selenium could also drive the browser the way I want it?”  Well, one advantage I appreciate is Capybara’s higher-level API compared to selenium.

Let’s take for example a simple scenario of typing strings to an input textbox:

Selenium-webdriver snippet

require 'selenium-webdriver'

element = driver.find_element :name => "q"
element.send_keys "Cucumber tests"

Capybara snippet

require 'capybara'

fill_in "q", "Cucumber tests"

You can obviously see from this example that Capybara enforces easier writing scripts ability. For a complete documentation on Capybara you can check this link from Github which I found very helpful.

After installation setup discussed in my previous post Introduction to Cucumber, you need to have the following folder structure and files:

I. Base Folder

Base Folder Structure


features – folder to host all your feature files

step_definitions – folder to host all your step definition Ruby files

support – folder to host your configuration files (env.rb)

Gemfile – defines the top-level gems to be used in your project

II. Features

– describes the features that a user will be able to use in the program

Sample: simple_search.feature

Feature: As a user I should be able to perform simple google search

Scenario: A simple google search scenario
 Given I am on the main google search
 When I fill in "q" with "Cucumber test"
 And I click "gbqfb" button
 And I click on the first result
 Then I should see "Cucumber lets software development teams describe how software should behave in plain text."

III. Step Definition

– describes the actions that user will do for each step.

Sample: search_step.rb

Given /^I am on the main google search$/ do
 visit ('/')

When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value|
 fill_in(field, :with => value)

Then /^I click "([^"]*)" button$/ do |button|

Then /^I click on the first result$/ do
 find(:xpath, "//html/body/div[3]/div[2]/div/div[5]/div[2]/div[2]/div/div[2]/div/ol/li/div/h3/a").click

Then /^I should see "([^"]*)"$/ do |text|
 page.should have_content(text)

IV. Support

– hosts all configuration files

Sample: env.rb

require 'capybara'
require 'capybara/cucumber'

Capybara.default_driver = :selenium
Capybara.app_host = ""
Capybara.default_wait_time = 20


V. Gemfile

– a format for describing gem dependencies required to execute Ruby codes

Sample: Gemfile

source ""

group(:test) do
 gem 'cucumber'
 gem 'capybara'
 gem 'rspec'

VI. Run

Using terminal go to your root project folder and type: cucumber or bundle exec cucumber

After the run, you should be able to see the results like this:

1 scenario (1 passed)
5 steps (5 passed)

This example runs smoothly in Windows 7. Let me know if it works for you as well.

Useful RubyMine Keyboard Shortcuts

September 14, 2012 Leave a comment

Meet my new colleague, Jetbrains RubyMine “The Most Intelligent Ruby on Rail IDE” sounds big huh! Since he will be my new companion / buddy for the next months to come, I decided to know him better and build a good rapport. 🙂

Here are some of the keyboard shortcuts I find to be friendly and useful:

Shortcut Description
Ctrl+Alt+S Go to Settings
Ctrl+N Open a class
Ctrl+Shift+N Open a file
Ctrl+B Go to declaration
Ctrl+Space Code completion
Ctrl+E Show recent files
Ctrl+K Commit changes
Ctrl+G Go to line
Ctrl+T Update project
Alt+Left/Right Navigate through the editor tabs
Ctrl+Slash Make a block comment
Ctrl+F Find from current file
Ctrl+Shift+F Find from current folder
Categories: ruby, technology Tags: ,

Error installing Nokogiri in Ubuntu 10.10

June 26, 2012 Leave a comment

Following Nokogiri Installation for Ubuntu I run below #nokogiri requirement in my terminal:

sudo apt-get install libxslt-dev libxml2-dev
sudo gem install nokogiri

Running “sudo gem install nokogiri” displays the following error:

Building native extensions.  This could take a while...
 ERROR:  Error installing nokogiri:
 ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb
 extconf.rb:5:in `require': no such file to load -- mkmf (LoadError)
 from extconf.rb:5
Gem files will remain installed in /var/lib/gems/1.8/gems/nokogiri- for inspection.
 Results logged to /var/lib/gems/1.8/gems/nokogiri-

Was able to resolve the issue by installing ruby1.8-dev and reinstalling the nokogiri gem:

sudo apt-get install ruby1.8-dev 
sudo gem install nokogiri 

exist@exist:~$ sudo gem install nokogiri
 Building native extensions.  This could take a while...
 Successfully installed nokogiri-1.4.4
 1 gem installed
 Installing ri documentation for nokogiri-1.4.4...
Categories: ruby, technology, ubuntu Tags: ,

Selenium-Ruby Installations in Linux

March 30, 2011 Leave a comment

In relation to my previous post on Selenium and Ruby setup in Windows, here’s an installation guide for Linux peeps:

1. Install JRE

– In your terminal type: sudo apt-get install sun-java6-jre

– To verify type: java -version

Note: Java version should be 1.5 or higher versions

2. Install Ruby

– In your terminal, type: sudo apt-get install ruby

– To verify type: ruby –version

Note: ruby 1.8.7 works with rspec version <= 1.3.1

3. Install Rubygems

– From the terminal, type: sudo apt-get install rubygems OR you can follow this tutorial Installing RubyGems

– To verify type:  gem –version

4. Install other useful gems

  • Rake ( to create a task that runs set of tests )

– Type: sudo gem install rake

– To verify type:  rake –version

  • Selenium-client ( API to drive Selenium tests from Ruby )

– Type: sudo gem install selenium-client -v 1.2.18

– To verify type: gem list selenium-client

Note: selenium-client 1.2.18 works with rspec version 1.2.8

  • Rspec ( to define executable examples of the expected behaviour of your code )

– Type: sudo gem install rspec -v 1.2.8

– To verify type: spec –version

  • Faker ( to easily generate fake data: names, addresses, phone numbers, etc. )

– Type: sudo gem install faker

– To verify type: gem list faker

Categories: ruby, selenium, ubuntu Tags: , , ,

Selenium and Ruby setup in Windows

September 4, 2009 2 comments

Newbie in Ruby? Never heard Selenium? Had a reformat?
No sweat! Here’s a list of requirements to set up Selenium and Ruby in your Windows machine.

SELENIUM Remote-Control (RC )

–> is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser.

  • extract the file anywhere in you local machine


–> Requirement to run the selenium server, should be 1.5 or later version

  • install Java and configure your PATH environment variable correctly.
  • from the console, you can verify the installation by typing:  java -version


  • requires Ruby


  • get the latest rubygem distribution as tgz or zip from here
  • extract the archive to your desired directory
  • 2 ways to install ruby:

from the console, go to the extracted directory then type:  ruby setup.rb

from your explorer, go to the extracted directory and double click setup.rb file

  • install the ruby client driver as a rubygem by typing:  gem install <ruby gem>

gem install selenium-client

  • install other gems that will be useful in your testing:

gem install rspec -v=1.2.6

gem install syntax

gem install faker

BDoc documentation

–> guide for all your rubygems documentations

  • from the console type: gem install aptinio-bdoc
  • then save the doc to your local, from the console  type:  bdoc //[path]

To get scripts or file from a repository through Git

  1. from the console, install github, bash or gui
  2. generate an SSH rsa, type: $ ssh-keygen -t rsa
  3. copy the generated id_rsa pub
  4. paste it on the personal settings of ur public_key
  5. then clone
Categories: ruby, selenium Tags: , , ,

Get all hyperlinks within a page using Nokogiri

August 27, 2009 Leave a comment

Task: Create a selenium script using Ruby that will collect all the available links within a page.

In essence we will try to create a method that will parse the html source of the current page and get all the elements with css(‘a’) or xpath ‘//a’ which indicates an anchor element. First let’s try to do it in IRB.


1. Start your server and fire up your irb

2. In your console, type

require 'nokogiri'

3. Initialize the page we want to test, say we want to get all the hyperlinks within a google home page.

page = ""

4. Type the following commands

doc = Nokogiri::HTML(open(page))
links = doc.css('a')
hrefs = {|link| link.attribute('href').to_s}.uniq.sort.delete_if
{|href| href.empty?}

Of course we would not like to do the procedure every time in our console, thus we could save it as a method in our class like the following:

# method that will get all links using Nokogiri
def get_all_hrefs_nokogiri
page = self.get_location()
doc = Nokogiri::HTML(open(page))
links = doc.css(‘a’)

hrefs = {|link| link.attribute(‘href’).to_s}.uniq.sort.delete_if {|href| href.empty?}
return hrefs

# get all links without using Nokogiri
def get_all_hrefs
hrefs = []
self.get_xpath_count(‘//a’).to_i.times do |i|
if self.is_element_present(“document.links[#{i}]”) {hrefs << self.get_attribute("document.links[#{i}]@href")} end return hrefs end end [/sourcecode]

Categories: ruby Tags: ,