[~/sinatra/sinatra-selenium/intro(master)]$ pwd -P /Users/casiano/local/src/ruby/sinatra/sinatra-selenium/intro
La forma mas simple de usar Capybara es instanciar un objeto Capybara::Session. A partir de ese momento es posible llamar a los métodos del DSL capybara sobre dicho objeto:
[~/sinatra/sinatra-selenium/intro(master)]$ cat -n hello_lpp.rb 1 require 'capybara' 2 session = Capybara::Session.new(:selenium) 3 session.visit "http://nereida.deioc.ull.es/~lpp/perlexamples/" 4 5 if session.has_content?("Apuntes de RUBY") 6 puts "All shiny, captain!" 7 else 8 puts ":( no tagline found, possibly something's broken" 9 exit(-1) 10 end
La clase Session
representa la interacción
de un único usuario con el sistema.
La Session
puede utilizar cualquiera de los drivers subyacentes.
Para inicializar manualmente una sesión podemos hacer algo como esto:
session = Capybara::Session.new(:culerity, MyRackApp)La aplicación que se pasa como segundo argumento es opcional.
Cuando se ejecuta Capybara contra una página externa como en el ejemplo deberemos omitirla.
session = Capybara::Session.new(:culerity) # Culerity is a gem that integrates Cucumber and Celerity # (Celerity is a headless Java browser with JavaScript support) # in order to test your application's full stack # including Javascript. session.visit('http://www.google.com')
Session
provee métodos para controlar la navegación
en la página como:
visit
, switch_to_window
etc.
Esto permite la interacción con la página:
session.fill_in('q', :with => 'Capybara') session.click_button('Search') expect(session).to have_content('Capybara')
También delega algunos métodos a la clase Capybara::Node::Document, que representa al documento HTML actual.
El código de delegación puede verse en el fichero lib/capybara/session.rb de la distribución de Capybara:
NODE_METHODS = [ :all, :first, :attach_file, :text, :check, :choose, :click_link_or_button, :click_button, :click_link, ... ] # @api private DOCUMENT_METHODS = [ :title, :assert_title, ... ] ... def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| define_method method do |*args, &block| @touched = true current_scope.send(method, *args, &block) end end DOCUMENT_METHODS.each do |method| define_method method do |*args, &block| document.send(method, *args, &block) end end def inspect %(#<Capybara::Session>) end def current_scope scopes.last || document end ... def scopes @scopes ||= [nil] end
session.visit(url)
navega a la URL dada.
La URL puede ser relativa o absoluta. La conducta depende del driver.
session.visit('/foo') session.visit('http://google.com')For drivers which can run against an external application, such as the selenium driver giving an absolute URL will navigate to that page.
Capybara.app_host
will make the remote server the default. For example:
Capybara.app_host = 'http://google.com' session.visit('/') # visits the google homepage
If Capybara.always_include_port
is set to true and this session is running against a rack application, then the port that the rack application is running on will automatically be inserted into the URL.
Supposing the app is running on port 4567
, doing something like:
visit("http://google.com/test")Will actually navigate to
google.com:4567/test
.
Entre las alternativas se encuentran:
Poltergeist is a headless browser driver for Capybara. You will need to
install PhantomJS and make sure that phantomjs
command is in your
path first.
El siguiente Rakefile muestra como Instalar phantomjs en un Mac:
[~/sinatra/sinatra-selenium/intro(master)]$ cat Rakefile desc "install phantomjs in a mac" task :phantom do sh "brew update && brew install phantomjs" end
A headless browser is a web browser without a graphical user interface. In other words it is a browser, a piece of software, that access web pages but doesn’t show them to any human being. They’re actually used to provide the content of web pages to other programs.
Este es el mismo ejemplo anterior pero usando
capybara/poltergeist
:
[~/sinatra/sinatra-selenium/intro(master)]$ cat -n hello_lpp_phantom.rb 1 require 'capybara' 2 require 'capybara/poltergeist' 3 4 session = Capybara::Session.new(:poltergeist) 5 6 session.visit "http://nereida.deioc.ull.es/~lpp/perlexamples/" 7 8 if session.has_content?("Apuntes de RUBY") 9 puts "All shiny, captain!" 10 else 11 puts ":( no tagline fonud, possibly something's broken" 12 exit(-1) 13 end
[~/sinatra/sinatra-selenium/intro(master)]$ cat Gemfile source 'https://rubygems.org' gem 'capybara' gem 'poltergeist'
Casiano Rodriguez León 2015-01-07