Test Automation with Cucumber & Capybara

We will introduce today Capybara an higher level ATDD testing framework
which support for multiple backends, supports Selenium and works in multiple browsers.

The advantage of using Capybara over selenium is being on higher level than selenium , it can be used for other types of automation beside browser automation without changing the user facing simple and intuitive DSL.
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"

The difference is clear in terms of simplicity and user friendliness which sets apart capaybara from selenium webdriver.Below is complete example for the reference starting from setting up the folder structure.
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]").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 = "http://www.google.com"
Capybara.default_wait_time = 20
V. Gemfile
- a format for describing gem dependencies required to execute Ruby codes
Sample: Gemfile

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)


Popular posts from this blog

Testing Webservice with SoapUI Having Windows Authentication

Data Driven Testing Using Selenium -WebDriver in Python

How to Re-run Failed Scenarios in Cucumber