Capybara – A User-Like Testing Application – Installation



Capybara – A User-Like Testing Application – Installation

0 0


extension_slides


On Github bryan-zake / extension_slides

Capybara

A User-Like Testing Application

Created and Presented by Reid Fu, Jimmy Kang, Chris Phillips, Jen Risch, and Bryan Zake

What is Capybara?

  • Integration testing tool for rack based web apps
    • Integration testing: phase in software testing in which software modules are tested as group
    • Also does acceptance testing (whether contract for component is met)
    • Rack: simple interface for handling HTTP in Ruby
  • Simulates user interaction with a website
    • Preview elements on web page
    • Perform actions on web page that user might do

Some Key Benefits

  • No setup needed in Rails/Rack apps
  • Simple to understand (API mimics language of actual user)
  • Backend (web driver) can be switched w/o changing tests

Installation

  • Requires Ruby 1.9.3+
  • 'gem install capybara' or add to Gemfile as gem 'capybara' and run 'bundle install'
  • On Rails, add the line require 'capybara/rails' to your test helper filetest/test_helper.rb

Drivers

Capybara.default_driver 
=>: rack_test

# Change default driver

Capybara.default_driver = :selenium

# Temporarily change the driver

Capybara.current_driver = :webkit
#Run some tests!
Capybara.use_default_driver

RackTest

  • Fast, but limited
  • No Javascript support
  • Server not required
  • Requires application to be a Rack application (e.g. Rails)
  • Not for remote uses
    • No HTTP access outside of Rack app

Selenium

  • Full browser
  • Install selenium-webdriver gem to useAdd to gemfile or do 'gem install selenium-webdriver'

Headless Drivers

Capybara-webkit

Uses QtWebKit to start rendering engineSignificantly faster than Selenium

gem install capybara-webkit

Capybara.javascript-driver = :webkit

Poltergeist

Uses PhantomJS a headless WebkitFast and native support for various web standards

  • DOM handling, CSS selectors, JSON, SVG

Adding and Configuring Drivers

#Overide selenium to use chrome
Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, :browser => :chrome)
end

#Switch browsers effortlessly
ruby Capybara.current_driver = :selenium_chrome

#Configure :rack_test headers
Capybara.register_driver :rack_test do |app|
  Capybara::RackTest::Driver.new(app, :headers => {'HTTP_USER_AGENT'
   => 'Capybara'})
end

The DSL(Domain Specific Language)

  • accessed through Session objects
  • classes using 'capybara/dsl' have default session

Common Method Parameters

  • locator: id, text, value of HTML element to find
  • options_hash: defaults to {}

Go Places, Click and Fill

  • visit(url)
    • Request method is always GET
    • Driver dependent behavior
  • click_link_or_button(locator, options_hash)
  • fill_in(locator, options_hash)
    • :with key required in options_hash; value used to fill in form

Select and Check

  • select/unselect(value, options_hash)
    • selects/unselects option associated with a value
    • :from key in options_hash is locator for list to select from
  • check/uncheck(locator, options_hash)

Do Things, Find Windows

#Executes commands within specific part of page
within(selector) do
...
end

#Returns window or tab reference
window_opened_by do
...
end

Example with Session

require 'capybara'
session = Capybara::Session.new :selenium
session.visit 'www.google.com'
session.click_link_or_button 'Sign in'
session.fill_in 'Email', :with => 'your email'
session.click_button 'Next'
session.fill_in 'Password', :with => 'your password'
session.click_button 'Sign in'
#Replace with assert
puts 'ha, I win'

Form Interaction

#Examples of tools for interacting with form elements
fill_in('Name', :with => 'John')
choose('A radio button')
check('A checkbox')
uncheck('A checkbox')
attach_file('Image', '/path/to/image.jpg')
select('Option', :from => 'Select Box')

Querying

#Examples of page querying for element existence and manipulation
page.has_selector?('table tr')
page.has_selector?(:xpath, '//table/tr')
page.has_xpath?('//table/tr')
page.has_css?('table tr.foo')
page.has_content?('foo')

Finding

#Examples of finding specific elements
find_field('Name').value
find_link('Hello', :visible => :all).visible?
find_button('Send').click
find(:xpath, "//table/tr").click
find("#overlay").find("h1").click
all('a').each { |a| a[:href] }

Modals

#Accept or dismiss alert messages by wrapping in a block:
accept_alert do
    click_link('Show Alert')
end

#Also accept or dismiss a confirmation in this way:
dismiss_confirm do
    click_link('Show Confirm')
end

Modals Continued

#Accept or dismiss prompts and provide text for the response:
accept_prompt(with: 'Response') do
    click_link('Show Prompt')
end

#Return and access the prompt message:
message = accept_prompt(with: 'Response') do
    click_link('Show Prompt')
end
expect(message).to eq('Prompt');

Debugging

#Take a snapshot and look at it:
save_and_open_page

#Retrieve the current state of the DOM as a string
print page.html

#Save a screenshot:
page.save_screenshot('screenshot.png')

#Save and open a screenshot:
save_and_open_screenshot

Matching

#When exact is false, it allows substring matches

#Also matches "Test Case"
Capybara.exact = true
click_link("Test Case")

#Only matches "Test"
Capybara.exact = false
click_link("Test")
  • Different matching schemes for Capybara.match
  • one: Gives error if more than one element matches
  • first: Picks the first element that matches
  • smart: if exact is true, acts like one otherwise tries to find an exact match
  • prefer_exact: finds all matching elements but returns only exact match and remaining elements are discarded.

Capybara with Frameworks

  • Supports Cucumber, RSpec, Test::Unit, and MiniTest
  • Each has it's own unique setup
  • We'll use minitest-rails-capybara

minitest-rails-capybara

  • Includes minitest, minitest-rails, minitest-capybara, and capybara
  gem install 'minitest-rails-capybara'

  #Put in Gemfile
  gem "minitest-rails"
  group :test do
    gem "minitest-rails-capybara"
  end

  #Put in test/test_helper.rb in rails app
  require minitest/rails/capybara

  $bundle install
minitest-rails-capybara

Generate tests

$ rails generate minitest:feature CanAccessIndex 
$ vim test/features/can_access_index_test.rb

require "test_helper"

class CanAccessIndexTest < Capybara::Rails::TestCase
  test "sanity" do
    visit root_path
    assert_content page, "Hello World"
    refute_content page, "Goobye All!"
  end
end

Generate different tests

$ rails generate minitest:feature CanAccessIndex --spec 
$ vim test/features/can_access_index_test.rb

#Generates a feature test using the Capybara spec DSL
require "test_helper"

feature "Can Access Index" do
  scenarion "has content" do
    visit root_path
    page.must_have_content "Home#index"
  end
end

Questions?

References

https://github.com/jnicklas/capybara

http://www.rubydoc.info/github/jnicklas/capybara/master

http://blowmage.com/minitest-rails-capybara/

Capybara A User-Like Testing Application Created and Presented by Reid Fu, Jimmy Kang, Chris Phillips, Jen Risch, and Bryan Zake