Automated Testing with Cucumber + Capybara
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:
require 'selenium-webdriver' element = driver.find_element :name => "q" element.send_keys "Cucumber tests"
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
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
– describes the features that a user will be able to use in the program
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.
Given /^I am on the main google search$/ do visit ('/') end When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value| fill_in(field, :with => value) end Then /^I click "([^"]*)" button$/ do |button| click_button(button) end Then /^I click on the first result$/ do find(:xpath, "//html/body/div/div/div/div/div/div/div/div/div/ol/li/div/h3/a").click end Then /^I should see "([^"]*)"$/ do |text| page.should have_content(text) end
– hosts all configuration files
require 'capybara' require 'capybara/cucumber' Capybara.default_driver = :selenium Capybara.app_host = "http://www.google.com" Capybara.default_wait_time = 20 World(Capybara)
– a format for describing gem dependencies required to execute Ruby codes
source "http://rubygems.org" group(:test) do gem 'cucumber' gem 'capybara' gem 'rspec' end
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.