Capybara is an acceptance test framework for web applications in Ruby. It integrates with Ruby-based BDD frameworks such as Cucumber and RSpec, along with Selenium WebDriver, for web testing capabilities. Capybara is widely used in testing Rails applications.
In this recipe, we will see how to use Capybara, Cucumber, and Selenium to test the BMI Calculator application.
gem install capybara
gem install cucumber gem install rspec
In Capybara, we need to create a features file for the stories under test. These stories are written in the Gherkin language with the Given
, When
, and Then
structures in the Cucumber format. Perform the following steps to create a feature and step definition file with Capybara:
BmiCalculate.feature
, as follows:Feature: BMI Calculator has a Calculate Function Scenario: Calculate BMI Given I am on BMI Calculator When I fill in the following: | heightCMS | 181 | | weightKg | 80 | When I press "Calculate" Then I should see following: | bmi | 24.4 | | bmi_category | Normal |
BmiCalculate.rb
:Given /^I am on BMI Calculator$/ do visit "http:// cookbook.seleniumacademy.com/bmicalculator.html" end When /^I fill in the following:$/ do |table| table.rows_hash.each {|field, value| fill_in field, :with => value } end When /^I press "([^"]*)"$/ do |button| click_button(button) end Then /^I should see following:$/ do |table| table.rows_hash.each {|field, value| find_field(field).value.should == value } end
env.rb
:require 'capybara' require 'capybara/cucumber' require 'selenium/webdriver' Capybara.default_driver = :selenium Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :firefox) end
We need to copy all of these files together in a directory named features
, and use the cucumber command, as follows:
cucumber
Since we are using Cucumber along with Capybara, it first needs feature files written in plain English. In the following example, we have a step which will populate the height
and weight
fields in the BMI Calculator application:
When I fill in the following: | heightCMS | 181 | | weightKg | 80 |
The steps from a feature file are then mapped to Capybara commands using a step file written in Ruby. In the following example, the previously mentioned table format is mapped to the Capybara command, fill_in
:
When /^I fill in the following:$/ do |table| table.rows_hash.each {|field, value| fill_in field, :with => value } end
To run these features with Cucumber, we need a configuration file that will tell Capybara to use Selenium as a driver:
require 'capybara' require 'capybara/cucumber' require 'selenium/webdriver' Capybara.default_driver = :selenium Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :firefox) end
When Cucumber runs the features, a default report is generated in the following format:
3.139.239.41