capybara-2.1.0/ 0000755 0001750 0001750 00000000000 12140721202 012307 5 ustar lunar lunar capybara-2.1.0/spec/ 0000755 0001750 0001750 00000000000 12140721202 013241 5 ustar lunar lunar capybara-2.1.0/spec/fixtures/ 0000755 0001750 0001750 00000000000 12140721202 015112 5 ustar lunar lunar capybara-2.1.0/spec/fixtures/selenium_driver_rspec_failure.rb 0000644 0001750 0001750 00000000321 12140721202 023532 0 ustar lunar lunar require 'spec_helper'
describe Capybara::Selenium::Driver do
it "should exit with a non-zero exit status" do
browser = Capybara::Selenium::Driver.new(TestApp).browser
true.should == false
end
end
capybara-2.1.0/spec/fixtures/selenium_driver_rspec_success.rb 0000644 0001750 0001750 00000000314 12140721202 023555 0 ustar lunar lunar require 'spec_helper'
describe Capybara::Selenium::Driver do
it "should exit with a zero exit status" do
browser = Capybara::Selenium::Driver.new(TestApp).browser
true.should == true
end
end
capybara-2.1.0/spec/spec_helper.rb 0000644 0001750 0001750 00000000174 12140721202 016061 0 ustar lunar lunar require "capybara/spec/spec_helper"
require "pry"
RSpec.configure do |config|
Capybara::SpecHelper.configure(config)
end
capybara-2.1.0/spec/rack_test_spec.rb 0000644 0001750 0001750 00000011353 12140721202 016562 0 ustar lunar lunar require 'spec_helper'
module TestSessions
RackTest = Capybara::Session.new(:rack_test, TestApp)
end
Capybara::SpecHelper.run_specs TestSessions::RackTest, "RackTest", :skip => [
:js,
:screenshot,
:frames,
:windows,
:server,
:hover
]
describe Capybara::Session do
context 'with rack test driver' do
before do
@session = TestSessions::RackTest
end
describe '#driver' do
it "should be a rack test driver" do
@session.driver.should be_an_instance_of(Capybara::RackTest::Driver)
end
end
describe '#mode' do
it "should remember the mode" do
@session.mode.should == :rack_test
end
end
describe '#click_link' do
it "should use data-method if option is true" do
@session.driver.options[:respect_data_method] = true
@session.visit "/with_html"
@session.click_link "A link with data-method"
@session.html.should include('The requested object was deleted')
end
it "should not use data-method if option is false" do
@session.driver.options[:respect_data_method] = false
@session.visit "/with_html"
@session.click_link "A link with data-method"
@session.html.should include('Not deleted')
end
it "should use data-method if available even if it's capitalized" do
@session.driver.options[:respect_data_method] = true
@session.visit "/with_html"
@session.click_link "A link with capitalized data-method"
@session.html.should include('The requested object was deleted')
end
after do
@session.driver.options[:respect_data_method] = false
end
end
describe "#attach_file" do
context "with multipart form" do
it "should submit an empty form-data section if no file is submitted" do
@session.visit("/form")
@session.click_button("Upload Empty")
@session.html.should include('Successfully ignored empty file field.')
end
end
end
end
end
describe Capybara::RackTest::Driver do
before do
@driver = TestSessions::RackTest.driver
end
describe ':headers option' do
it 'should always set headers' do
@driver = Capybara::RackTest::Driver.new(TestApp, :headers => {'HTTP_FOO' => 'foobar'})
@driver.visit('/get_header')
@driver.html.should include('foobar')
end
it 'should keep headers on link clicks' do
@driver = Capybara::RackTest::Driver.new(TestApp, :headers => {'HTTP_FOO' => 'foobar'})
@driver.visit('/header_links')
@driver.find_xpath('.//a').first.click
@driver.html.should include('foobar')
end
it 'should keep headers on form submit' do
@driver = Capybara::RackTest::Driver.new(TestApp, :headers => {'HTTP_FOO' => 'foobar'})
@driver.visit('/header_links')
@driver.find_xpath('.//input').first.click
@driver.html.should include('foobar')
end
it 'should keep headers on redirects' do
@driver = Capybara::RackTest::Driver.new(TestApp, :headers => {'HTTP_FOO' => 'foobar'})
@driver.visit('/get_header_via_redirect')
@driver.html.should include('foobar')
end
end
describe ':follow_redirects option' do
it "defaults to following redirects" do
@driver = Capybara::RackTest::Driver.new(TestApp)
@driver.visit('/redirect')
@driver.response.header['Location'].should be_nil
@driver.browser.current_url.should match %r{/landed$}
end
it "is possible to not follow redirects" do
@driver = Capybara::RackTest::Driver.new(TestApp, :follow_redirects => false)
@driver.visit('/redirect')
@driver.response.header['Location'].should match %r{/redirect_again$}
@driver.browser.current_url.should match %r{/redirect$}
end
end
describe ':redirect_limit option' do
context "with default redirect limit" do
before do
@driver = Capybara::RackTest::Driver.new(TestApp)
end
it "should follow 5 redirects" do
@driver.visit("/redirect/5/times")
@driver.html.should include('redirection complete')
end
it "should not follow more than 6 redirects" do
expect do
@driver.visit("/redirect/6/times")
end.to raise_error(Capybara::InfiniteRedirectError)
end
end
context "with 21 redirect limit" do
before do
@driver = Capybara::RackTest::Driver.new(TestApp, :redirect_limit => 21)
end
it "should follow 21 redirects" do
@driver.visit("/redirect/21/times")
@driver.html.should include('redirection complete')
end
it "should not follow more than 21 redirects" do
expect do
@driver.visit("/redirect/22/times")
end.to raise_error(Capybara::InfiniteRedirectError)
end
end
end
end
capybara-2.1.0/spec/rspec_spec.rb 0000644 0001750 0001750 00000002531 12140721202 015715 0 ustar lunar lunar require 'spec_helper'
describe 'capybara/rspec', :type => :feature do
it "should include Capybara in rspec" do
visit('/foo')
page.body.should include('Another World')
end
context "resetting session" do
it "sets a cookie in one example..." do
visit('/set_cookie')
page.body.should include('Cookie set to test_cookie')
end
it "...then it is not availbable in the next" do
visit('/get_cookie')
page.body.should_not include('test_cookie')
end
end
context "setting the current driver" do
it "sets the current driver in one example..." do
Capybara.current_driver = :selenium
end
it "...then it has returned to the default in the next example" do
Capybara.current_driver.should == :rack_test
end
end
it "switches to the javascript driver when giving it as metadata", :js => true do
Capybara.current_driver.should == Capybara.javascript_driver
end
it "switches to the given driver when giving it as metadata", :driver => :culerity do
Capybara.current_driver.should == :culerity
end
end
describe 'capybara/rspec', :type => :other do
it "should not include Capybara" do
expect { visit('/') }.to raise_error(NoMethodError)
end
end
feature "Feature DSL" do
scenario "is pulled in" do
visit('/foo')
page.body.should include('Another World')
end
end
capybara-2.1.0/spec/basic_node_spec.rb 0000644 0001750 0001750 00000010505 12140721202 016667 0 ustar lunar lunar require 'spec_helper'
describe Capybara do
describe '.string' do
let :string do
Capybara.string <<-STRING
simple_node
Totally awesome
Yes it is
Secret
STRING
end
it "allows using matchers" do
string.should have_css('#page')
string.should_not have_css('#does-not-exist')
end
it "allows using custom matchers" do
Capybara.add_selector :lifeform do
xpath { |name| "//option[contains(.,'#{name}')]" }
end
string.should have_selector(:id, "page")
string.should_not have_selector(:id, 'does-not-exist')
string.should have_selector(:lifeform, "Monkey")
string.should_not have_selector(:lifeform, "Gorilla")
end
it 'allows custom matcher using css' do
Capybara.add_selector :section do
css { |css_class| "section .#{css_class}" }
end
string.should have_selector(:section, 'subsection')
string.should_not have_selector(:section, 'section_8')
end
it "allows using matchers with text option" do
string.should have_css('h1', :text => 'Totally awesome')
string.should_not have_css('h1', :text => 'Not so awesome')
end
it "allows finding only visible nodes" do
string.all(:css, '#secret', :visible => true).should be_empty
string.all(:css, '#secret', :visible => false).should have(1).element
end
it "allows finding elements and extracting text from them" do
string.find('//h1').text.should == 'Totally awesome'
end
it "allows finding elements and extracting attributes from them" do
string.find('//h1')[:data].should == 'fantastic'
end
it "allows finding elements and extracting the tag name from them" do
string.find('//h1').tag_name.should == 'h1'
end
it "allows finding elements and extracting the path" do
string.find('//h1').path.should == '/html/body/div/div[1]/h1'
end
it "allows finding elements and extracting the path" do
string.find('//div/input').value.should == 'bar'
string.find('//select').value.should == 'Capybara'
end
it "allows finding elements and checking if they are visible" do
string.find('//h1').should be_visible
string.find(:css, "#secret", :visible => false).should_not be_visible
end
it "allows finding elements and checking if they are disabled" do
string.find('//form/input[@name="bleh"]').should be_disabled
string.find('//form/input[@name="meh"]').should_not be_disabled
end
describe "#title" do
it "returns the page title" do
string.title.should == "simple_node"
end
end
describe "#has_title?" do
it "returns whether the page has the given title" do
string.has_title?('simple_node').should be_true
string.has_title?('monkey').should be_false
end
it "allows regexp matches" do
string.has_title?(/s[a-z]+_node/).should be_true
string.has_title?(/monkey/).should be_false
end
end
describe '#has_no_title?' do
it "returns whether the page does not have the given title" do
string.has_no_title?('simple_node').should be_false
string.has_no_title?('monkey').should be_true
end
it "allows regexp matches" do
string.has_no_title?(/s[a-z]+_node/).should be_false
string.has_no_title?(/monkey/).should be_true
end
end
end
end
capybara-2.1.0/spec/dsl_spec.rb 0000644 0001750 0001750 00000016137 12140721202 015372 0 ustar lunar lunar require 'spec_helper'
require 'capybara/dsl'
class TestClass
include Capybara::DSL
end
Capybara::SpecHelper.run_specs TestClass.new, "DSL", :skip => [
:js,
:screenshot,
:frames,
:windows,
:server,
:hover
]
describe Capybara::DSL do
after do
Capybara.session_name = nil
Capybara.default_driver = nil
Capybara.javascript_driver = nil
Capybara.use_default_driver
Capybara.app = TestApp
end
describe '#default_driver' do
it "should default to rack_test" do
Capybara.default_driver.should == :rack_test
end
it "should be changeable" do
Capybara.default_driver = :culerity
Capybara.default_driver.should == :culerity
end
end
describe '#current_driver' do
it "should default to the default driver" do
Capybara.current_driver.should == :rack_test
Capybara.default_driver = :culerity
Capybara.current_driver.should == :culerity
end
it "should be changeable" do
Capybara.current_driver = :culerity
Capybara.current_driver.should == :culerity
end
end
describe '#javascript_driver' do
it "should default to selenium" do
Capybara.javascript_driver.should == :selenium
end
it "should be changeable" do
Capybara.javascript_driver = :culerity
Capybara.javascript_driver.should == :culerity
end
end
describe '#use_default_driver' do
it "should restore the default driver" do
Capybara.current_driver = :culerity
Capybara.use_default_driver
Capybara.current_driver.should == :rack_test
end
end
describe '#using_driver' do
before do
Capybara.current_driver.should_not == :selenium
end
it 'should set the driver using Capybara.current_driver=' do
driver = nil
Capybara.using_driver(:selenium) { driver = Capybara.current_driver }
driver.should == :selenium
end
it 'should return the driver to default if it has not been changed' do
Capybara.using_driver(:selenium) do
Capybara.current_driver.should == :selenium
end
Capybara.current_driver.should == Capybara.default_driver
end
it 'should reset the driver even if an exception occurs' do
driver_before_block = Capybara.current_driver
begin
Capybara.using_driver(:selenium) { raise "ohnoes!" }
rescue Exception
end
Capybara.current_driver.should == driver_before_block
end
it 'should return the driver to what it was previously' do
Capybara.current_driver = :selenium
Capybara.using_driver(:culerity) do
Capybara.using_driver(:rack_test) do
Capybara.current_driver.should == :rack_test
end
Capybara.current_driver.should == :culerity
end
Capybara.current_driver.should == :selenium
end
it 'should yield the passed block' do
called = false
Capybara.using_driver(:selenium) { called = true }
called.should == true
end
end
describe '#using_wait_time' do
before do
@previous_wait_time = Capybara.default_wait_time
end
after do
Capybara.default_wait_time = @previous_wait_time
end
it "should switch the wait time and switch it back" do
in_block = nil
Capybara.using_wait_time 6 do
in_block = Capybara.default_wait_time
end
in_block.should == 6
Capybara.default_wait_time.should == @previous_wait_time
end
it "should ensure wait time is reset" do
expect do
Capybara.using_wait_time 6 do
raise "hell"
end
end.to raise_error
Capybara.default_wait_time.should == @previous_wait_time
end
end
describe '#app' do
it "should be changeable" do
Capybara.app = "foobar"
Capybara.app.should == 'foobar'
end
end
describe '#current_session' do
it "should choose a session object of the current driver type" do
Capybara.current_session.should be_a(Capybara::Session)
end
it "should use #app as the application" do
Capybara.app = proc {}
Capybara.current_session.app.should == Capybara.app
end
it "should change with the current driver" do
Capybara.current_session.mode.should == :rack_test
Capybara.current_driver = :selenium
Capybara.current_session.mode.should == :selenium
end
it "should be persistent even across driver changes" do
object_id = Capybara.current_session.object_id
Capybara.current_session.object_id.should == object_id
Capybara.current_driver = :selenium
Capybara.current_session.mode.should == :selenium
Capybara.current_session.object_id.should_not == object_id
Capybara.current_driver = :rack_test
Capybara.current_session.object_id.should == object_id
end
it "should change when changing application" do
object_id = Capybara.current_session.object_id
Capybara.current_session.object_id.should == object_id
Capybara.app = proc {}
Capybara.current_session.object_id.should_not == object_id
Capybara.current_session.app.should == Capybara.app
end
it "should change when the session name changes" do
object_id = Capybara.current_session.object_id
Capybara.session_name = :administrator
Capybara.session_name.should == :administrator
Capybara.current_session.object_id.should_not == object_id
Capybara.session_name = :default
Capybara.session_name.should == :default
Capybara.current_session.object_id.should == object_id
end
end
describe "#using_session" do
it "should change the session name for the duration of the block" do
Capybara.session_name.should == :default
Capybara.using_session(:administrator) do
Capybara.session_name.should == :administrator
end
Capybara.session_name.should == :default
end
it "should reset the session to the default, even if an exception occurs" do
begin
Capybara.using_session(:raise) do
raise
end
rescue Exception
end
Capybara.session_name.should == :default
end
it "should yield the passed block" do
called = false
Capybara.using_session(:administrator) { called = true }
called.should == true
end
end
describe "#session_name" do
it "should default to :default" do
Capybara.session_name.should == :default
end
end
describe 'the DSL' do
before do
@session = Class.new { include Capybara::DSL }.new
end
it "should be possible to include it in another class" do
@session.visit('/with_html')
@session.click_link('ullamco')
@session.body.should include('Another World')
end
it "should provide a 'page' shortcut for more expressive tests" do
@session.page.visit('/with_html')
@session.page.click_link('ullamco')
@session.page.body.should include('Another World')
end
it "should provide an 'using_session' shortcut" do
Capybara.should_receive(:using_session).with(:name)
@session.using_session(:name)
end
it "should provide a 'using_wait_time' shortcut" do
Capybara.should_receive(:using_wait_time).with(6)
@session.using_wait_time(6)
end
end
end
capybara-2.1.0/spec/result_spec.rb 0000644 0001750 0001750 00000001664 12140721202 016125 0 ustar lunar lunar require 'spec_helper'
describe Capybara::Result do
let :string do
Capybara.string <<-STRING
Alpha
Beta
Gamma
Delta
STRING
end
let :result do
string.all '//li'
end
it "has a length" do
result.length.should == 4
end
it "has a first element" do
result.first.text == 'Alpha'
end
it "has a last element" do
result.last.text == 'Delta'
end
it "can return an element by its index" do
result.at(1).text.should == 'Beta'
result[2].text.should == 'Gamma'
end
it "can be mapped" do
result.map(&:text).should == %w(Alpha Beta Gamma Delta)
end
it "can be selected" do
result.select do |element|
element.text.include? 't'
end.length.should == 2
end
it "can be reduced" do
result.reduce('') do |memo, element|
memo += element.text[0]
end.should == 'ABGD'
end
end
capybara-2.1.0/spec/capybara_spec.rb 0000644 0001750 0001750 00000002615 12140721202 016366 0 ustar lunar lunar require 'spec_helper'
describe Capybara do
describe 'default_wait_time' do
after do
Capybara.default_wait_time = @previous_default_time
end
it "should be changeable" do
@previous_default_time = Capybara.default_wait_time
Capybara.default_wait_time = 5
Capybara.default_wait_time.should == 5
end
end
describe '.register_driver' do
it "should add a new driver" do
Capybara.register_driver :schmoo do |app|
Capybara::RackTest::Driver.new(app)
end
session = Capybara::Session.new(:schmoo, TestApp)
session.visit('/')
session.body.should include("Hello world!")
end
end
describe ".server" do
after do
Capybara.server {|app, port| Capybara.run_default_server(app, port)}
end
it "should default to a proc that calls run_default_server" do
mock_app = mock('app')
Capybara.should_receive(:run_default_server).with(mock_app, 8000)
Capybara.server.call(mock_app, 8000)
end
it "should return a custom server proc" do
server = lambda {|app, port|}
Capybara.server(&server)
Capybara.server.should == server
end
end
end
describe Capybara::Session do
context 'with non-existant driver' do
it "should raise an error" do
expect {
Capybara::Session.new(:quox, TestApp).driver
}.to raise_error(Capybara::DriverNotFoundError)
end
end
end
capybara-2.1.0/spec/rspec/ 0000755 0001750 0001750 00000000000 12140721202 014355 5 ustar lunar lunar capybara-2.1.0/spec/rspec/features_spec.rb 0000644 0001750 0001750 00000003022 12140721202 017527 0 ustar lunar lunar require 'spec_helper'
require 'capybara/rspec'
RSpec.configuration.before(:each, :example_group => {:file_path => "./spec/rspec/features_spec.rb"}) do
@in_filtered_hook = true
end
feature "Capybara's feature DSL" do
background do
@in_background = true
end
scenario "includes Capybara" do
visit('/')
page.should have_content('Hello world!')
end
scenario "preserves description" do
example.metadata[:full_description].should == "Capybara's feature DSL preserves description"
end
scenario "allows driver switching", :driver => :selenium do
Capybara.current_driver.should == :selenium
end
scenario "runs background" do
@in_background.should be_true
end
scenario "runs hooks filtered by file path" do
@in_filtered_hook.should be_true
end
scenario "doesn't pollute the Object namespace" do
Object.new.respond_to?(:feature, true).should be_false
end
end
feature "given and given! aliases to let and let!" do
given(:value) { :available }
given!(:value_in_background) { :available }
background do
value_in_background.should be(:available)
end
scenario "given and given! work as intended" do
value.should be(:available)
value_in_background.should be(:available)
end
end
feature "if xscenario aliases to pending then" do
xscenario "this test should be 'temporarily disabled with xscenario'" do
end
end
feature "Capybara's feature DSL with driver", :driver => :culerity do
scenario "switches driver" do
Capybara.current_driver.should == :culerity
end
end
capybara-2.1.0/spec/rspec/matchers_spec.rb 0000644 0001750 0001750 00000051175 12140721202 017533 0 ustar lunar lunar require 'spec_helper'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
describe Capybara::RSpecMatchers do
include Capybara::DSL
include Capybara::RSpecMatchers
describe "have_css matcher" do
it "gives proper description" do
have_css('h1').description.should == "have css \"h1\""
end
context "on a string" do
context "with should" do
it "passes if has_css? returns true" do
"
Text
".should have_css('h1')
end
it "fails if has_css? returns false" do
expect do
"
Text
".should have_css('h2')
end.to raise_error(/expected to find css "h2" but there were no matches/)
end
it "passes if matched node count equals expected count" do
"
Text
".should have_css('h1', :count => 1)
end
it "fails if matched node count does not equal expected count" do
expect do
"
Text
".should have_css('h1', count: 2)
end.to raise_error("expected to find css \"h1\" 2 times, found 1 match: \"Text\"")
end
it "fails if matched node count is less than expected minimum count" do
expect do
"
Text
".should have_css('p', minimum: 1)
end.to raise_error("expected to find css \"p\" at least 1 time but there were no matches")
end
it "fails if matched node count is more than expected maximum count" do
expect do
"
Text
Text
Text
".should have_css('h1', maximum: 2)
end.to raise_error('expected to find css "h1" at most 2 times, found 3 matches: "Text", "Text", "Text"')
end
it "fails if matched node count does not belong to expected range" do
expect do
"
Text
".should have_css('h1', between: 2..3)
end.to raise_error("expected to find css \"h1\" between 2 and 3 times, found 1 match: \"Text\"")
end
end
context "with should_not" do
it "passes if has_no_css? returns true" do
"
Text
".should_not have_css('h2')
end
it "fails if has_no_css? returns false" do
expect do
"
Text
".should_not have_css('h1')
end.to raise_error(/expected not to find css "h1"/)
end
it "passes if matched node count does not equal expected count" do
"
Text
".should_not have_css('h1', :count => 2)
end
it "fails if matched node count equals expected count" do
expect do
"
Text
".should_not have_css('h1', :count => 1)
end.to raise_error(/expected not to find css "h1"/)
end
end
end
context "on a page or node" do
before do
visit('/with_html')
end
context "with should" do
it "passes if has_css? returns true" do
page.should have_css('h1')
end
it "fails if has_css? returns false" do
expect do
page.should have_css('h1#doesnotexist')
end.to raise_error(/expected to find css "h1#doesnotexist" but there were no matches/)
end
end
context "with should_not" do
it "passes if has_no_css? returns true" do
page.should_not have_css('h1#doesnotexist')
end
it "fails if has_no_css? returns false" do
expect do
page.should_not have_css('h1')
end.to raise_error(/expected not to find css "h1"/)
end
end
end
end
describe "have_xpath matcher" do
it "gives proper description" do
have_xpath('//h1').description.should == "have xpath \"\/\/h1\""
end
context "on a string" do
context "with should" do
it "passes if has_xpath? returns true" do
"
Text
".should have_xpath('//h1')
end
it "fails if has_xpath? returns false" do
expect do
"
Text
".should have_xpath('//h2')
end.to raise_error(%r(expected to find xpath "//h2" but there were no matches))
end
end
context "with should_not" do
it "passes if has_no_xpath? returns true" do
"
Text
".should_not have_xpath('//h2')
end
it "fails if has_no_xpath? returns false" do
expect do
"
Text
".should_not have_xpath('//h1')
end.to raise_error(%r(expected not to find xpath "//h1"))
end
end
end
context "on a page or node" do
before do
visit('/with_html')
end
context "with should" do
it "passes if has_xpath? returns true" do
page.should have_xpath('//h1')
end
it "fails if has_xpath? returns false" do
expect do
page.should have_xpath("//h1[@id='doesnotexist']")
end.to raise_error(%r(expected to find xpath "//h1\[@id='doesnotexist'\]" but there were no matches))
end
end
context "with should_not" do
it "passes if has_no_xpath? returns true" do
page.should_not have_xpath('//h1[@id="doesnotexist"]')
end
it "fails if has_no_xpath? returns false" do
expect do
page.should_not have_xpath('//h1')
end.to raise_error(%r(expected not to find xpath "//h1"))
end
end
end
end
describe "have_selector matcher" do
it "gives proper description" do
matcher = have_selector('//h1')
"
Text
".should matcher
matcher.description.should == "have xpath \"//h1\""
end
context "on a string" do
context "with should" do
it "passes if has_selector? returns true" do
"
Text
".should have_selector('//h1')
end
it "fails if has_selector? returns false" do
expect do
"
Text
".should have_selector('//h2')
end.to raise_error(%r(expected to find xpath "//h2" but there were no matches))
end
end
context "with should_not" do
it "passes if has_no_selector? returns true" do
"
Text
".should_not have_selector(:css, 'h2')
end
it "fails if has_no_selector? returns false" do
expect do
"
Text
".should_not have_selector(:css, 'h1')
end.to raise_error(%r(expected not to find css "h1"))
end
end
end
context "on a page or node" do
before do
visit('/with_html')
end
context "with should" do
it "passes if has_selector? returns true" do
page.should have_selector('//h1', :text => 'test')
end
it "fails if has_selector? returns false" do
expect do
page.should have_selector("//h1[@id='doesnotexist']")
end.to raise_error(%r(expected to find xpath "//h1\[@id='doesnotexist'\]" but there were no matches))
end
it "includes text in error message" do
expect do
page.should have_selector("//h1", :text => 'wrong text')
end.to raise_error(%r(expected to find xpath "//h1" with text "wrong text" but there were no matches))
end
end
context "with should_not" do
it "passes if has_no_css? returns true" do
page.should_not have_selector(:css, 'h1#doesnotexist')
end
it "fails if has_no_selector? returns false" do
expect do
page.should_not have_selector(:css, 'h1', :text => 'test')
end.to raise_error(%r(expected not to find css "h1" with text "test"))
end
end
end
end
describe "have_content matcher" do
it "gives proper description" do
have_content('Text').description.should == "text \"Text\""
end
context "on a string" do
context "with should" do
it "passes if has_content? returns true" do
"
Text
".should have_content('Text')
end
it "passes if has_content? returns true using regexp" do
"
Text
".should have_content(/ext/)
end
it "fails if has_content? returns false" do
expect do
"
Text
".should have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "Text"/)
end
end
context "with should_not" do
it "passes if has_no_content? returns true" do
"
Text
".should_not have_content('No such Text')
end
it "passes because escapes any characters that would have special meaning in a regexp" do
"
Text
".should_not have_content('.')
end
it "fails if has_no_content? returns false" do
expect do
"
Text
".should_not have_content('Text')
end.to raise_error(/expected not to find text "Text" in "Text"/)
end
end
end
context "on a page or node" do
before do
visit('/with_html')
end
context "with should" do
it "passes if has_content? returns true" do
page.should have_content('This is a test')
end
it "passes if has_content? returns true using regexp" do
page.should have_content(/test/)
end
it "fails if has_content? returns false" do
expect do
page.should have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
context "with default selector CSS" do
before { Capybara.default_selector = :css }
it "fails if has_content? returns false" do
expect do
page.should have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
after { Capybara.default_selector = :xpath }
end
end
context "with should_not" do
it "passes if has_no_content? returns true" do
page.should_not have_content('No such Text')
end
it "fails if has_no_content? returns false" do
expect do
page.should_not have_content('This is a test')
end.to raise_error(/expected not to find text "This is a test"/)
end
end
end
end
describe "have_text matcher" do
it "gives proper description" do
have_text('Text').description.should == "text \"Text\""
end
context "on a string" do
context "with should" do
it "passes if has_text? returns true" do
"
Text
".should have_text('Text')
end
it "passes if has_text? returns true using regexp" do
"
Text
".should have_text(/ext/)
end
it "fails if has_text? returns false" do
expect do
"
Text
".should have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "Text"/)
end
it "casts Fixnum to string" do
expect do
"
Text
".should have_text(3)
end.to raise_error(/expected to find text "3" in "Text"/)
end
it "fails if matched text count does not equal to expected count" do
expect do
"
Text
".should have_text('Text', count: 2)
end.to raise_error(/expected to find text "Text" 2 times in "Text"/)
end
it "fails if matched text count is less than expected minimum count" do
expect do
"
Text
".should have_text('Lorem', minimum: 1)
end.to raise_error(/expected to find text "Lorem" at least 1 time in "Text"/)
end
it "fails if matched text count is more than expected maximum count" do
expect do
"
Text TextText
".should have_text('Text', maximum: 2)
end.to raise_error(/expected to find text "Text" at most 2 times in "Text TextText"/)
end
it "fails if matched text count does not belong to expected range" do
expect do
"
Text
".should have_text('Text', between: 2..3)
end.to raise_error(/expected to find text "Text" between 2 and 3 times in "Text"/)
end
end
context "with should_not" do
it "passes if has_no_text? returns true" do
"
Text
".should_not have_text('No such Text')
end
it "passes because escapes any characters that would have special meaning in a regexp" do
"
Text
".should_not have_text('.')
end
it "fails if has_no_text? returns false" do
expect do
"
Text
".should_not have_text('Text')
end.to raise_error(/expected not to find text "Text" in "Text"/)
end
end
end
context "on a page or node" do
before do
visit('/with_html')
end
context "with should" do
it "passes if has_text? returns true" do
page.should have_text('This is a test')
end
it "passes if has_text? returns true using regexp" do
page.should have_text(/test/)
end
it "can check for all text" do
page.should have_text(:all, 'Some of this text is hidden!')
end
it "can check for visible text" do
page.should have_text(:visible, 'Some of this text is')
page.should_not have_text(:visible, 'Some of this text is hidden!')
end
it "fails if has_text? returns false" do
expect do
page.should have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
context "with default selector CSS" do
before { Capybara.default_selector = :css }
it "fails if has_text? returns false" do
expect do
page.should have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
after { Capybara.default_selector = :xpath }
end
end
context "with should_not" do
it "passes if has_no_text? returns true" do
page.should_not have_text('No such Text')
end
it "fails if has_no_text? returns false" do
expect do
page.should_not have_text('This is a test')
end.to raise_error(/expected not to find text "This is a test"/)
end
end
end
end
describe "have_link matcher" do
let(:html) { 'Just a link' }
it "gives proper description" do
have_link('Just a link').description.should == "have link \"Just a link\""
end
it "passes if there is such a button" do
html.should have_link('Just a link')
end
it "fails if there is no such button" do
expect do
html.should have_link('No such Link')
end.to raise_error(/expected to find link "No such Link"/)
end
end
describe "have_title matcher" do
it "gives proper description" do
have_title('Just a title').description.should == "have title \"Just a title\""
end
context "on a string" do
let(:html) { 'Just a title' }
it "passes if there is such a title" do
html.should have_title('Just a title')
end
it "fails if there is no such title" do
expect do
html.should have_title('No such title')
end.to raise_error(/expected there to be title "No such title"/)
end
end
context "on a page or node" do
before do
visit('/with_js')
end
it "passes if there is such a title" do
page.should have_title('with_js')
end
it "fails if there is no such title" do
expect do
page.should have_title('No such title')
end.to raise_error(/expected there to be title "No such title"/)
end
end
end
describe "have_button matcher" do
let(:html) { '' }
it "gives proper description" do
have_button('A button').description.should == "have button \"A button\""
end
it "passes if there is such a button" do
html.should have_button('A button')
end
it "fails if there is no such button" do
expect do
html.should have_button('No such Button')
end.to raise_error(/expected to find button "No such Button"/)
end
end
describe "have_field matcher" do
let(:html) { '' }
it "gives proper description" do
have_field('Text field').description.should == "have field \"Text field\""
end
it "passes if there is such a field" do
html.should have_field('Text field')
end
it "fails if there is no such field" do
expect do
html.should have_field('No such Field')
end.to raise_error(/expected to find field "No such Field"/)
end
end
describe "have_checked_field matcher" do
let(:html) do
'
'
end
it "gives proper description" do
have_checked_field('it is checked').description.should == "have field \"it is checked\""
end
context "with should" do
it "passes if there is such a field and it is checked" do
html.should have_checked_field('it is checked')
end
it "fails if there is such a field but it is not checked" do
expect do
html.should have_checked_field('unchecked field')
end.to raise_error(/expected to find field "unchecked field"/)
end
it "fails if there is no such field" do
expect do
html.should have_checked_field('no such field')
end.to raise_error(/expected to find field "no such field"/)
end
end
context "with should not" do
it "fails if there is such a field and it is checked" do
expect do
html.should_not have_checked_field('it is checked')
end.to raise_error(/expected not to find field "it is checked"/)
end
it "passes if there is such a field but it is not checked" do
html.should_not have_checked_field('unchecked field')
end
it "passes if there is no such field" do
html.should_not have_checked_field('no such field')
end
end
end
describe "have_unchecked_field matcher" do
let(:html) do
'
'
end
it "gives proper description" do
have_unchecked_field('unchecked field').description.should == "have field \"unchecked field\""
end
context "with should" do
it "passes if there is such a field and it is not checked" do
html.should have_unchecked_field('unchecked field')
end
it "fails if there is such a field but it is checked" do
expect do
html.should have_unchecked_field('it is checked')
end.to raise_error(/expected to find field "it is checked"/)
end
it "fails if there is no such field" do
expect do
html.should have_unchecked_field('no such field')
end.to raise_error(/expected to find field "no such field"/)
end
end
context "with should not" do
it "fails if there is such a field and it is not checked" do
expect do
html.should_not have_unchecked_field('unchecked field')
end.to raise_error(/expected not to find field "unchecked field"/)
end
it "passes if there is such a field but it is checked" do
html.should_not have_unchecked_field('it is checked')
end
it "passes if there is no such field" do
html.should_not have_unchecked_field('no such field')
end
end
end
describe "have_select matcher" do
let(:html) { '' }
it "gives proper description" do
have_select('Select Box').description.should == "have select box \"Select Box\""
end
it "passes if there is such a select" do
html.should have_select('Select Box')
end
it "fails if there is no such select" do
expect do
html.should have_select('No such Select box')
end.to raise_error(/expected to find select box "No such Select box"/)
end
end
describe "have_table matcher" do
let(:html) { '
Lovely table
' }
it "gives proper description" do
have_table('Lovely table').description.should == "have table \"Lovely table\""
end
it "passes if there is such a select" do
html.should have_table('Lovely table')
end
it "fails if there is no such select" do
expect do
html.should have_table('No such Table')
end.to raise_error(/expected to find table "No such Table"/)
end
end
end
capybara-2.1.0/spec/server_spec.rb 0000644 0001750 0001750 00000006505 12140721202 016114 0 ustar lunar lunar require 'spec_helper'
describe Capybara::Server do
it "should spool up a rack server" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app).boot
@res = Net::HTTP.start(@server.host, @server.port) { |http| http.get('/') }
@res.body.should include('Hello Server')
end
it "should do nothing when no server given" do
expect do
@server = Capybara::Server.new(nil).boot
end.not_to raise_error
end
it "should bind to the specified host" do
Capybara.server_host = '0.0.0.0'
app = proc { |env| [200, {}, ["Hello Server!"]]}
server = Capybara::Server.new(app).boot
server.host.should == '0.0.0.0'
Capybara.server_host = nil
end
it "should use specified port" do
Capybara.server_port = 22789
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app).boot
@res = Net::HTTP.start(@server.host, 22789) { |http| http.get('/') }
@res.body.should include('Hello Server')
Capybara.server_port = nil
end
it "should use given port" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app, 22790).boot
@res = Net::HTTP.start(@server.host, 22790) { |http| http.get('/') }
@res.body.should include('Hello Server')
Capybara.server_port = nil
end
it "should find an available port" do
@app1 = proc { |env| [200, {}, ["Hello Server!"]]}
@app2 = proc { |env| [200, {}, ["Hello Second Server!"]]}
@server1 = Capybara::Server.new(@app1).boot
@server2 = Capybara::Server.new(@app2).boot
@res1 = Net::HTTP.start(@server1.host, @server1.port) { |http| http.get('/') }
@res1.body.should include('Hello Server')
@res2 = Net::HTTP.start(@server2.host, @server2.port) { |http| http.get('/') }
@res2.body.should include('Hello Second Server')
end
it "should use the server if it already running" do
@app1 = proc { |env| [200, {}, ["Hello Server!"]]}
@app2 = proc { |env| [200, {}, ["Hello Second Server!"]]}
@server1a = Capybara::Server.new(@app1).boot
@server1b = Capybara::Server.new(@app1).boot
@server2a = Capybara::Server.new(@app2).boot
@server2b = Capybara::Server.new(@app2).boot
@res1 = Net::HTTP.start(@server1b.host, @server1b.port) { |http| http.get('/') }
@res1.body.should include('Hello Server')
@res2 = Net::HTTP.start(@server2b.host, @server2b.port) { |http| http.get('/') }
@res2.body.should include('Hello Second Server')
@server1a.port.should == @server1b.port
@server2a.port.should == @server2b.port
end
it "should raise server errors when the server errors before the timeout" do
begin
Capybara.server do
sleep 0.1
raise 'kaboom'
end
proc do
Capybara::Server.new(proc {|e|}).boot
end.should raise_error(RuntimeError, 'kaboom')
ensure
# TODO refactor out the defaults so it's reliant on unset state instead of
# a one-time call in capybara.rb
Capybara.server {|app, port| Capybara.run_default_server(app, port)}
end
end
it "is not #responsive? when Net::HTTP raises a SystemCallError" do
app = lambda { [200, {}, ['Hello, world']] }
server = Capybara::Server.new(app)
Net::HTTP.should_receive(:start).and_raise(SystemCallError.allocate)
expect(server.responsive?).to eq false
end
end
capybara-2.1.0/spec/selenium_spec.rb 0000644 0001750 0001750 00000002354 12140721202 016425 0 ustar lunar lunar require 'spec_helper'
module TestSessions
Selenium = Capybara::Session.new(:selenium, TestApp)
end
Capybara::SpecHelper.run_specs TestSessions::Selenium, "selenium", :skip => [
:response_headers,
:status_code,
:trigger
]
describe Capybara::Session do
context 'with selenium driver' do
before do
@session = TestSessions::Selenium
end
describe '#driver' do
it "should be a selenium driver" do
@session.driver.should be_an_instance_of(Capybara::Selenium::Driver)
end
end
describe '#mode' do
it "should remember the mode" do
@session.mode.should == :selenium
end
end
describe "exit codes" do
before do
@current_dir = Dir.getwd
Dir.chdir(File.join(File.dirname(__FILE__), '..'))
end
after do
Dir.chdir(@current_dir)
end
it "should have return code 1 when running selenium_driver_rspec_failure.rb" do
`rspec spec/fixtures/selenium_driver_rspec_failure.rb`
$?.exitstatus.should be 1
end
it "should have return code 0 when running selenium_driver_rspec_success.rb" do
`rspec spec/fixtures/selenium_driver_rspec_success.rb`
$?.exitstatus.should be 0
end
end
end
end
capybara-2.1.0/History.md 0000644 0001750 0001750 00000060057 12140721202 014302 0 ustar lunar lunar # Version 2.1.0
Release date: Unreleased
### Changed
* Hard version requirement on Ruby >= 1.9.3. Capybara will no longer install
on 1.8.7. [Felix Schäfer]
* Capybara no longer depends on the `selenium-webdriver` gem. Add it to
your Gemfile if you wish to use the Selenium driver. [Jonas Nicklas]
* `Capybara.ignore_hidden_elements` defaults to `true`. [Jonas Nicklas]
* In case of multiple matches `smart` matching is used by default. Set
`Capybara.match = :one` to revert to old behaviour. [Jonas Nicklas].
* Options in select boxes use smart matching and no longer need to match
exactly. Set `Capybara.exact_options = false` to revert to old behaviour.
[Jonas Nicklas].
* Visibility of text depends on `Capybara.ignore_hidden_elements` instead of
always returning only visible text. Set `Capybara.visible_text_only = true`
to revert to old behaviour. [Jonas Nicklas]
* Cucumber cleans up session after scenario instead. This is consistent with
RSpec and makes more sense, since we raise server errors in `reset!`.
[Jonas Nicklas]
### Added
* All actions (`click_link`, `fill_in`, etc...) and finders now take an options
hash, which is passed through to `find`. [Jonas Nicklas]
* CSS selectors are sent straight through to driver instead of being converted
to XPath first. Enables the use of some pseudo selectors, such as `invalid`
in some drivers. [Thomas Walpole]
* `Capybara.asset_host` option, which inserts a `base` tag into the page on
`save_and_open_page`, eases debugging with the Rails asset pipeline.
[Steve Hull]
* `exact` option, can specify whether to match substrings or entire text.
[Jonas Nicklas]
* `match` option, can specify behaviour in case of multiple matches.
[Jonas Nicklas]
* `wait` option, can specify how long to wait for a given action/finder.
[Jonas Nicklas]
* Config option which disables bubbling of errors raised inside server.
[Jonas Nicklas]
* `text` now takes a parameter which makes it possible to return either all
text or only visible text. The default depends on
`Capybara.ignore_hidden_elements`. `Capybara.visible_text_only` option is
available for compatibility. [Jonas Nicklas]
* `has_content?` and `has_text?` now take the same count options as `has_selector?`
[Andrey Botalov]
* `current_scope` is now public API, returns the current element when `within`
is used. [Martijn Walraven]
* `find("input").disabled?` returns true if a node is disabled. [Ben Lovell]
* Find disabled fields and buttons with `:disabled => false`. [Jonas Nicklas]
* `find("input").hover` moves the mouse to the element in supported drivers.
[Thomas Walpole]
* RackTest driver now support `form` attribute on form elements.
[Thomas Walpole]
* `page.title` returns the page title. [Terry Progetto]
* `has_title?` matcher to assert on page title. [Jonas Nicklas]
* The gem is now signed with a certicficate. The public key is available in the
repo. [Jonas Nicklas]
* `:select` and `:textarea` are valid options for the `:type` filter on `find_field`
and `has_field?`. [Yann Plancqueel]
### Fixed
* Fixed race conditions when synchronizing across multiple nodes [Jonas Nicklas]
* Fixed race conditions in deeply nested selectors [Jonas Nicklas]
* Fix issue with `within_frame`, where selecting multiple nested frames didn't
work as intended. [Thomas Walpole]
* RackTest no longer fills in readonly textareas. [Thomas Walpole]
* Don't use autoload to load files, require them directly instead. [Jonas Nicklas]
* Rescue weird exceptions when booting server [John Wilger]
* Non strings are now properly cast when using the maxlength attribute [Jonas Nicklas]
# Version 2.0.3
Release date: 2013-03-26
* Check against Rails version fixed to work with Rails' master branch now returning
a Gem::Version [Jonas Nicklas]
* Use posix character class for whitespace replace, solves various encoding
problems on Ruby 2.0.0 and JRuby. [Ben Cates]
# Version 2.0.2
Release date: 2012-12-31
### Changed
* Capybara no longer uses thin as a server if it is available, due to thread
safety issues. Now Capybara always defaults to WEBrick. [Jonas Nicklas]
### Fixed
* Suppress several warnings [Kouhei Sutou]
* Fix default host becoming nil [Brian Cardarella]
* Fix regression in 2.0.1 which caused node comparisons with non node objects
to throw an exception [Kouhei Sotou]
* A few changes to the specs, only relevant to driver authors [Jonas Nicklas]
* Encoding error under JRuby [Piotr Krawiec]
* Ruby 2 encoding fix [Murahashi Sanemat Kenichi]
* Catch correct exception on server timeout [Jonathan del Strother]
# Version 2.0.1
Release date: 2012-12-21
### Changed
* Move the RackTest driver override with the `:respect_data_method` option
enabled from capybara/rspec to capybara/rails, so that it is enabled in
Rails projects that don't use RSpec. [Carlos Antonio da Silva]
* `source` is now an alias for `html`. RackTest no longer returns modifications
to `html`. This basically codifies the behaviour which we've had for a while
anyway, and should have minimal impact for end users. For driver authors, it
means that they only have to implement `html`, and not `source`. [Jonas
Nicklas]
### Fixed
* Visiting relative URLs when `app_host` is set and no server is running works
as expected. [Jonas Nicklas]
* `fill_in` works properly under Selenium again when the caret is not at the
end of the field before the method is called. [Douwe Maan, Jonas Nicklas, Jari
Bakken]
* `attach_file` can once again be given a Pathname [Jake Goulding]
# Version 2.0.0
Release date: 2012-11-05
### Changed
* Dropped official support for Ruby 1.8.x. [Jonas Nicklas]
* `respect_data_method` default to `false` for the RackTest driver in non-rails
applications. That means that Capybara no longer picks up `data-method="post"`
et. al. from links by default when you haven't required capybara/rails
[Jonas Nicklas]
* `find` now raises an error if more than one element was found. Since `find` is
used by most actions, like `click_link` under the surface, this means that all
actions need to unambiguous in the future. [Jonas Nicklas]
* All methods which find or manipulate fields or buttons now ignore them when
they are disabled. [Jonas Nicklas]
* Can no longer find elements by id via `find(:foo)`, use `find("#foo")` or
`find_by_id("foo")` instead. [Jonas Nicklas]
* `Element#text` on RackTest now only returns visible text and normalizes
(strips) whitespace, as with Selenium [Mark Dodwell, Jo Liss]
* `has_content?` now checks the text value returned by `Element#text`, as opposed to
querying the DOM. Which means it does not match hidden text.
[Ryan Montgomery, Mark Dodwell, Jo Liss]
* #394: `#body` now returns the unmodified source (like `#source`), not the current
state of the DOM (like `#html`), by popular request [Jonas Nicklas]
* `Node#all` no longer returns an array, but rather an enumerable `Capybara::Result`
[Jonas Nicklas]
* The arguments to `select` and `unselect` needs to be the exact text of an option
in a select box, substrings are no longer allowed [Jonas Nicklas]
* The `options` option to `has_select?` must match the exact set of options. Use
`with_options` for the old behaviour. [Gonzalo Rodriguez]
* The `selected` option to `has_select?` must match all selected options for multiple
selects. [Gonzalo Rodriguez]
* Various internals for running driver specs, this should only affect driver authors
[Jonas Nicklas]
* Rename `Driver#body` to `Driver#html` (relevant only for driver authors) [Jo
Liss]
### Removed
* No longer possible to specify `failure_message` for custom selectors. [Jonas Nicklas]
* #589: `Capybara.server_boot_timeout` has been removed in favor of a higher
(60-second) hard-coded timeout [Jo Liss]
* `Capybara.prefer_visible_elements` has been removed, as it is no longer needed
with the changed find semantics [Jonas Nicklas]
* `Node#wait_until` and `Session#wait_until` have been removed. See `Node#synchronize`
for an alternative [Jonas Nicklas]
* `Capybara.timeout` has been removed [Jonas Nicklas]
* The `:resynchronize` option has been removed from the Selenium driver [Jonas Nicklas]
* The `rows` option to `has_table?` has been removed without replacement.
[Jonas Nicklas]
### Added
* Much improved error message [Jonas Nicklas]
* Errors from inside the session for apps running in a server are raised when
session is reset [James Tucker, Jonas Nicklas]
* A ton of new selectors built in out of the box, like `field`, `link`, `button`,
etc... [Adam McCrea, Jonas Nicklas]
* `has_text?` has been added as an alias for `has_content?` [Jonas Nicklas]
* Add `Capybara.server_host` option (default: 127.0.0.1) [David Balatero]
* Add `:type` option for `page.has_field?` [Gonzalo Rodríguez]
* Custom matchers can now be specified in CSS in addition to XPath [Jonas Nicklas]
* `Node#synchronize` method to rerun a block of code if certain errors are raised
[Jonas Nicklas]
* `Capybara.always_include_port` config option always includes the server port in
URLs when using `visit`. Facilitates testing different domain names`. [Douwe Maan]
* Redirect limit for RackTest driver is configurable [Josh Lane]
* Server port can be manually specified during initialization of server.
[Jonas Nicklas, John Wilger]
* `has_content?` and `has_text?` can be given a regular expression [Vasiliy Ermolovich]
* Multiple files can be uploaded with `attach_file` [Jarl Friis]
### Fixed
* Nodes found via `all` are no longer reloaded. This fixes weird quirks where
nodes would seemingly randomly replace themselves with other nodes [Jonas Nicklas]
* Session is only reset if it has been modified, dramatically improves performance if
only part of the test suite runs Capybara. [Jonas Nicklas]
* Test suite now passes on Ruby 1.8 [Jo Liss]
* #565: `require 'capybara/dsl'` is no longer necessary [Jo Liss]
* `Rack::Test` now respects ports when changing hosts [Jo Liss]
* #603: `Rack::Test` now preserves the original referer URL when following a
redirect [Rob van Dijk]
* Rack::Test now does not send a referer when calling `visit` multiple times
[Jo Liss]
* Exceptions during server boot now propagate to main thread [James Tucker]
* RSpec integration now cleans up before the test instead of after [Darwin]
* If `respect_data_method` is true, the data-method attribute can be capitalized
[Marco Antonio]
* Rack app boot timing out raises an error as opposed to just logging to STDOUT
[Adrian Irving-Beer]
* `#source` returns an empty string instead of nil if no pages have been visited
[Jonas Nicklas]
* Ignore first leading newline in textareas in RackTest [Vitalii Khustochka]
* `within_frame` returns the value of the given block [Alistair Hutchison]
* Running `Node.set` on text fields will not trigger more than one change event
[Andrew Kasper]
* Throw an error when an option is given to a finder method, like `all` or
`has_selector?` which Capybara doesn't understand [Jonas Nicklas]
* Two references to the node now register as equal when comparing them with `==`
[Jonas Nicklas]
* `has_text` (`has_content`) now accepts non-string arguments, like numbers.
[Jo Liss]
* `has_text` and `text` now correctly normalize Unicode whitespace, such as
` `. [Jo Liss]
* RackTest allows protocol relative URLs [Jonas Nicklas]
* Arguments are cast to string where necessary, so that e.g. `click_link(:foo)` works
as expected. [Jonas Nicklas]
* `:count => 0` now works as expected [Jarl Friis]
* Fixed race conditions on negative assertions when removing nodes [Jonas Nicklas]
# Version 1.1.4
Release date: 2012-11-28
### Fixed
* Fix more race conditions on negative assertions. [Jonas Nicklas]
# Version 1.1.3
Release date: 2012-10-30
### Fixed:
* RackTest driver ignores leading newline in textareas, this is consistent with
the spec and how browsers behave. [Vitalii Khustochka]
* Nodes found via `all` and `first` are never reloaded. This fixes issues where
a node would sometimes magically turn into a completely different node.
[Jonas Nicklas]
* Fix race conditions on negative assertions. This fixes issues where removing
an element and asserting on its non existence could cause
StaleElementReferenceError and similar to be thrown. [Jonas Nicklas]
* Options are no longer lost when reloading elements. This fixes issues where
reloading an element would cause a non-matching element to be found, because
options to `find` were ignored. [Jonas Nicklas]
# Version 1.1.2
Release date: 2011-11-15
### Fixed
* #541: Make attach_file work with selenium-webdriver >=2.12 [Jonas Nicklas]
# Version 1.1.0
Release date: 2011-09-02
### Fixed
* Sensible inspect for Capybara::Session [Jo Liss]
* Fix headers and host on redirect [Matt Colyer, Jonas Nicklas, Kim Burgestrand]
* using_driver now restores the old driver instead of reverting to the default [Carol Nichols]
* Errors when following links relative to the root path under rack-test [Jonas Nicklas, Kim Burgestrand]
* Make sure exit codes are propagated properly [Edgar Beigarts]
### Changed
* resynchronization is off by default under Selenium
### Added
* Elements are automatically reloaded (including parents) during wait [Jonas Nicklas]
* Rescue driver specific element errors, such as the dreaded ObsoleteElementError and retry [Jonas Nicklas]
* Raise an error if something has frozen time [Jonas Nicklas]
* Allow within to take a node instead of a selector [Peter Williams]
* Using wait_time_time to change wait time for a block of code [Jonas Nicklas, Kim Burgestrand]
* Option for rack-test driver to disable data-method hack [Jonas Nicklas, Kim Burgestrand]
# Version 1.0.1
Release date: 2011-08-12
### Fixed
* Dependend on selenium-webdriver ~>2.0 and fix deprecations [Thomas Walpole, Jo Liss]
* Depend on Launch 2.0 [Jeremy Hinegardner]
* Rack-Test ignores fill in on fields with maxlength=""
# Version 1.0.0
Release date: 2011-06-14
### Added
* Added DSL for acceptance tests, inspired by Luismi Cavallé's Steak [Luismi Cavalle and Jonas Nicklas]
* Selenium driver automatically waits for AJAX requests to finish [mgiambalvo, Nicklas Ramhöj and Jonas Nicklas]
* Support for switching between multiple named sessions [Tristan Dunn]
* failure_message can be specified for Selectors [Jonas Nicklas]
* RSpec matchers [David Chelimsky and Jonas Nicklas]
* Added save_page to save tempfile without opening in browser [Jeff Kreeftmeijer]
* Cucumber now switches automatically to a registered driver if the tag matches the name [Jonas Nicklas]
* Added Session#text [Jonas Nicklas and Scott Cytacki]
* Added Session#html as an alias for Session#body [Jo Liss]
* Added Session#current_host method [Jonas Nicklas]
* Buttons can now be clicked by title [Javier Martin]
* :headers option for RackTest driver to set custom HTTP headers [Jonas Nicklas]
### Removed
* Culerity and Celerity drivers have been removed and split into separate gems [Gabriel Sobrinho]
### Deprecated
* `include Capybara` has been deprecated in favour of `include Capybara::DSL` [Jonas Nicklas]
### Changed
* Rack test driver class has been renamed from Capybara::Driver::RackTest to Capybara::RackTest::Driver [Jonas Nicklas]
* Selenium driver class has been renamed from Capybara::Driver::Selenium to Capybara::Selenium::Driver [Jonas Nicklas]
* Capybara now prefers visible elements over hidden elements, disable by setting Capybara.prefer_visible_elements = false [Jonas Nicklas and Nicklas Ramhöj]
* For RSpec, :type => :request is now supported (and preferred over :acceptance) [Jo Liss]
* Selenium driver tried to wait for AJAX requests to finish before proceeding [Jonas Nicklas and Nicklas Ramhöj]
* Session no longer uses method missing, uses explicit delegates instead [Jonas Nicklas]
### Fixed
* The Rack::Test driver now respects maxlength on text fields [Guilherme Carvalho]
* Allow for more than one save_and_open_page call per second [Jo Liss]
* Automatically convert options to :count, :minimum, :maximum, etc. to integers [Keith Marcum]
* Rack::Test driver honours maxlength on input fields [Guilherme Carvalho]
* Rack::Test now works as expected with domains and subdomains [Jonas Nicklas]
* Session is reset more thoroughly between tests. [Jonas Nicklas]
* Raise error when uploading non-existant file [Jonas Nicklas]
* Rack reponse body should respond to #each [Piotr Sarnacki]
* Deprecation warnings with selenium webdriver 0.2.0 [Aaron Gibraltar]
* Selenium Chrome no longer YELLS tagname [Carl Jackson & David W. Frank]
* Capybara no longer strips encoding before sending to Rack [Jonas Nicklas]
* Improve handling of relative URLs [John Barton]
* Readd and fix build_rack_mock_session [Jonas Nicklas, Jon Leighton]
# Version 0.4.1
Release date: 2011-01-21
### Added
* New click_on alias for click_link_or_button, shorter yet unambiguous. [Jonas Nicklas]
* Finders now accept :visible => false which will find all elements regardless of Capybara.ignore_hidden_elements [Jonas Nicklas]
* Configure how the server is started via Capybara.server { |app, port| ... }. [John Firebough]
* Added :between, :maximum and :minimum options to has_selector and friends [James B. Byrne]
* New Capybara.string util function which allows matchers on arbitrary strings, mostly for helper and view specs [David Chelimsky and Jonas Nicklas]
* Server boot timeout is now configurable, via Capybara.server_boot_timeout [Adam Cigánek]
* Built in support for RSpec [Jonas Nicklas]
* Capybara.using_driver to switch to a different driver temporarily [Jeff Kreeftmeijer]
* Added Session#first which is somewhat speedier than Session#all, use it internally for speed boost [John Firebaugh]
### Changed
* Session#within now accepts the same arguments as other finders, like Session#all and Session#find [Jonas Nicklas]
### Removed
* All deprecations from 0.4.0 have been removed. [Jonas Nicklas]
### Fixed
* Don't mangle URLs in save_and_open_page when using self-closing tags [Adam Spiers]
* Catch correct error when server boot times out [Jonas Nicklas]
* Celerity driver now properly passes through options, making it configurable [Jonas Nicklas]
* Better implementation of attributes in C[ue]lerity, should fix issues with attributes with strange names [Jonas Nicklas]
* Session#find no longer swallows errors [Jonas Nicklas]
* Fix problems with multiple file inputs [Philip Arndt]
* Submit multipart forms as multipart under rack-test even if they contain no files [Ryan Kinderman]
* Matchers like has_select? and has_checked_field? now work with dynamically changed values [John Firebaugh]
* Preserve order of rack params [Joel Chippindale]
* RackTest#reset! is more thorough [Joel Chippindale]
# Version 0.4.0
Release date: 2010-10-22
### Changed
* The Selector API was changed slightly, use Capybara.add_selector, see README
### Fixed
* Celerity driver is registered properly
* has_selector? and has_no_selector? added to DSL
* Multiple selects return correct values under C[cu]lerity
* Naked query strings are handled correctly by rack-test
# Version 0.4.0.rc
Release date: 2010-10-12
### Changed
* within and find/locate now follow the XPath spec in that //foo finds all nodes in the document, instead of
only for the context node. See this post for details: http://groups.google.com/group/ruby-capybara/browse_thread/thread/b129067979df21b3
* within now executes within the first found instance of the selector, not in all of them
* find now waits for AJAX requests and raises an exception when the element is not found (same as locate used to do)
* The default selector is now CSS, not XPath
### Deprecated
* Session#click has been renamed click_link_or_button and the old click has been deprecated
* Node#node has been renamed native
* Node#locate is deprecated in favor of Node#find, which now behaves identically
* Session#drag is deprecated, please use Node#drag_to(other_node) instead
### Added
* Pretty much everything is properly documented now
* It's now possible to call all session methods on nodes, like `find('#foo').fill_in(...)`
* Custom selectors can be added with Capybara::Selector.add
* The :id selector is added by default, use it lile `find(:id, 'foo')` or `find(:foo)`
* Added Node#has_selector? so any kind of selector can be queried.
* Added Capybara.configure for less wordy configuration
* Added within_window to switch between different windows (currently Selenium only)
* Capybara.server_port to provide a fixed port if wanted (defaults to automatic selection)
### Fixed
* CSS selectors with multiple selectors, such as "h1, h2" now work correctly
* Port is automatically assigned instead of guessing
* Strip encodings in rack-test, no more warnings!
* RackTest no longer submits disabled fields
* Servers no longer output annoying debug information when started
* TCP port selection is left to Ruby to decide, no more port guessing
* Select boxes now return option value instead of text if present
* The default has been changed from localhost to 127.0.0.1, should fix some obscure selenium bugs
* RackTest now supports complex field names, such as foo[bar][][baz]
# Version 0.3.9
Release date: 2010-07-03
### Added
* status_code which returns the HTTP status code of the last response (no Selenium!)
* Capybara.save_and_open_page to store tempfiles
* RackTest and Culerity drivers now clean up after themselves properly
### Fixed
* When no rack app is set and the app is called, a more descriptive error is raised
* select now works with optgroups
* Don't submit image buttons unless they were clicked under rack-test
* Support custom field types under Selenium
* Support input fields without a type, treat them as though they were text fields
* Redirect now throws an error after 5 redirects, as per RFC
* Selenium now properly raises an error when Node#trigger is called
* Node#value now returns the correct value for textareas under rack-test
# Version 0.3.8
Release date: 2010-05-12
### Added
* Within_frame method to execute a block of code within a particular iframe (Selenium only!)
### Fixed
* Single quotes are properly escaped with `select` under rack-test and Selenium.
* The :text option for searches now escapes regexp special characters when a string is given.
* Selenium now correctly checks already checked checkboxes (same with uncheck)
* Timing issue which caused Selenium to hang under certain circumstances.
* Selenium now resolves attributes even if they are given as a Symbol
# Version 0.3.7
Release date: 2010-04-09
This is a drop in compatible maintainance release. It's mostly
important for driver authors.
### Added
* RackTest scans for data-method which rails3 uses to change the request method
### Fixed
* Don't hang when starting server on Windoze
### Changed
* The driver and session specs are now located inside lib! Driver authors can simply require them.
# Version 0.3.6
Release date: 2010-03-22
This is a maintainance release with minor bug fixes, should be
drop in compatible.
### Added
* It's now possible to load in external drivers
### Fixed
* has_content? ignores whitespace
* Trigger events when choosing radios and checking checkboxes under Selenium
* Make Capybara.app totally optional when running without server
* Changed fallback host so it matches the one set up by Rails' integration tests
# Version 0.3.5
Release date: 2010-02-26
This is a mostly backwards compatible release, it does break
the API in some minor places, which should hopefully not affect
too many users, please read the release notes carefully!
### Breaking
* Relative searching in a node (e.g. find('//p').all('//a')) will now follow XPath standard
this means that if you want to find descendant nodes only, you'll need to prefix a dot!
* `visit` now accepts fully qualified URLs for drivers that support it.
* Capybara will always try to run a rack server, unless you set Capybara.run_sever = false
### Changed
* thin is preferred over mongrel and webrick, since it is Ruby 1.9 compatible
* click_button and click will find , clicking them does nothing in RackTest
### Added
* Much improved error messages in a multitude of places
* More semantic page querying with has_link?, has_button?, etc...
* Option to ignore hidden elements when querying and interacting with the page
* Support for multiple selects
### Fixed
* find_by_id is no longer broken
* clicking links where the image's alt attribute contains the text is now possible
* within_fieldset and within_table work when the default selector is CSS
* boolean attributes work the same across drivers (return true/false)
capybara-2.1.0/README.md 0000644 0001750 0001750 00000064041 12140721202 013573 0 ustar lunar lunar # Capybara
[](http://travis-ci.org/jnicklas/capybara)
[](https://gemnasium.com/jnicklas/capybara)
[](https://codeclimate.com/github/jnicklas/capybara)
Capybara helps you test web applications by simulating how a real user would
interact with your app. It is agnostic about the driver running your tests and
comes with Rack::Test and Selenium support built in. WebKit is supported
through an external gem.
**Need help?** Ask on the mailing list (please do not open an issue on
GitHub): http://groups.google.com/group/ruby-capybara
## Key benefits
- **No setup** necessary for Rails and Rack application. Works out of the box.
- **Intuitive API** which mimics the language an actual user would use.
- **Switch the backend** your tests run against from fast headless mode
to an actual browser with no changes to your tests.
- **Powerful synchronization** features mean you never have to manually wait
for asynchronous processes to complete.
## Setup
Capybara requires Ruby 1.9.3 or later. To install, type:
```bash
gem install capybara
```
If the application that you are testing is a Rails app, add this line to your test helper file:
```ruby
require 'capybara/rails'
```
If the application that you are testing is a Rack app, but not Rails, set Capybara.app to your Rack app:
```ruby
Capybara.app = MyRackApp
```
If you need to test JavaScript, or if your app interacts with (or is located at)
a remote URL, you'll need to [use a different driver](#drivers).
## Using Capybara with Cucumber
The `cucumber-rails` gem comes with Capybara support built-in. If you
are not using Rails, manually load the `capybara/cucumber` module:
```ruby
require 'capybara/cucumber'
Capybara.app = MyRackApp
```
You can use the Capybara DSL in your steps, like so:
```ruby
When /I sign in/ do
within("#session") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
```
You can switch to the `Capybara.javascript_driver` (`:selenium`
by default) by tagging scenarios (or features) with `@javascript`:
```ruby
@javascript
Scenario: do something Ajaxy
When I click the Ajax link
...
```
There are also explicit `@selenium` and `@rack_test`
tags set up for you.
## Using Capybara with RSpec
Load RSpec 2.x support by adding the following line (typically to your
`spec_helper.rb` file):
```ruby
require 'capybara/rspec'
```
If you are using Rails, put your Capybara specs in `spec/features`.
If you are not using Rails, tag all the example groups in which you want to use
Capybara with `:type => :feature`.
You can now write your specs like so:
```ruby
describe "the signup process", :type => :feature do
before :each do
User.make(:email => 'user@example.com', :password => 'caplin')
end
it "signs me in" do
visit '/sessions/new'
within("#session") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
page.should have_content 'Success'
end
end
```
Use `:js => true` to switch to the `Capybara.javascript_driver`
(`:selenium` by default), or provide a `:driver` option to switch
to one specific driver. For example:
```ruby
describe 'some stuff which requires js', :js => true do
it 'will use the default js driver'
it 'will switch to one specific driver', :driver => :webkit
end
```
Finally, Capybara also comes with a built in DSL for creating descriptive acceptance tests:
```ruby
feature "Signing up" do
background do
User.make(:email => 'user@example.com', :password => 'caplin')
end
scenario "Signing in with correct credentials" do
visit '/sessions/new'
within("#session") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'caplin'
end
click_link 'Sign in'
page.should have_content 'Success'
end
given(:other_user) { User.make(:email => 'other@example.com', :password => 'rous') }
scenario "Signing in as another user" do
visit '/sessions/new'
within("#session") do
fill_in 'Login', :with => other_user.email
fill_in 'Password', :with => other_user.password
end
click_link 'Sign in'
page.should have_content 'Invalid email or password'
end
end
```
`feature` is in fact just an alias for `describe ..., :type => :feature`,
`background` is an alias for `before`, `scenario` for `it`, and
`given`/`given!` aliases for `let`/`let!`, respectively.
## Using Capybara with Test::Unit
* If you are using Rails, add the following code in your `test_helper.rb`
file to make Capybara available in all test cases deriving from
`ActionDispatch::IntegrationTest`:
```ruby
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
end
```
* If you are not using Rails, define a base class for your Capybara tests like
so:
```ruby
class CapybaraTestCase < Test::Unit::TestCase
include Capybara::DSL
def teardown
Capybara.reset_sessions!
Capybara.use_default_driver
end
end
```
Remember to call `super` in any subclasses that override
`teardown`.
To switch the driver, set `Capybara.current_driver`. For instance,
```ruby
class BlogTest < ActionDispatch::IntegrationTest
setup do
Capybara.current_driver = Capybara.javascript_driver # :selenium by default
end
test 'shows blog posts' do
# ... this test is run with Selenium ...
end
end
```
## Using Capybara with MiniTest::Spec
Set up your base class as with Test::Unit. (On Rails, the right base class
could be something other than ActionDispatch::IntegrationTest.)
The capybara_minitest_spec gem ([Github](https://github.com/ordinaryzelig/capybara_minitest_spec),
[rubygems.org](https://rubygems.org/gems/capybara_minitest_spec)) provides MiniTest::Spec
expectations for Capybara. For example:
```ruby
page.must_have_content('Important!')
```
## Drivers
Capybara uses the same DSL to drive a variety of browser and headless drivers.
### Selecting the Driver
By default, Capybara uses the `:rack_test` driver, which is fast but limited: it
does not support JavaScript, nor is it able to access HTTP resources outside of
your Rack application, such as remote APIs and OAuth services. To get around
these limitations, you can set up a different default driver for your features.
For example if you'd prefer to run everything in Selenium, you could do:
```ruby
Capybara.default_driver = :selenium
```
However, if you are using RSpec or Cucumber, you may instead want to consider
leaving the faster `:rack_test` as the __default_driver__, and marking only those
tests that require a JavaScript-capable driver using `:js => true` or
`@javascript`, respectively. By default, JavaScript tests are run using the
`:selenium` driver. You can change this by setting
`Capybara.javascript_driver`.
You can also change the driver temporarily (typically in the Before/setup and
After/teardown blocks):
```ruby
Capybara.current_driver = :webkit # temporarily select different driver
... tests ...
Capybara.use_default_driver # switch back to default driver
```
**Note**: switching the driver creates a new session, so you may not be able to
switch in the middle of a test.
### RackTest
RackTest is Capybara's default driver. It is written in pure Ruby and does not
have any support for executing JavaScript. Since the RackTest driver interacts
directly with Rack interfaces, it does not require a server to be started.
However, this means that if your application is not a Rack application (Rails,
Sinatra and most other Ruby frameworks are Rack applications) then you cannot
use this driver. Furthermore, you cannot use the RackTest driver to test a
remote application, or to access remote URLs (e.g., redirects to external
sites, external APIs, or OAuth services) that your application might interact
with.
[capybara-mechanize](https://github.com/jeroenvandijk/capybara-mechanize)
provides a similar driver that can access remote servers.
RackTest can be configured with a set of headers like this:
```ruby
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app, :browser => :chrome)
end
```
See the section on adding and configuring drivers.
### Selenium
At the moment, Capybara supports [Selenium 2.0
(Webdriver)](http://seleniumhq.org/docs/01_introducing_selenium.html#selenium-2-aka-selenium-webdriver),
*not* Selenium RC. Provided Firefox is installed, everything is set up for you,
and you should be able to start using Selenium right away.
**Note**: drivers which run the server in a different thread may not work share the
same transaction as your tests, causing data not to be shared between your test
and test server, see "Transactions and database setup" below.
### Capybara-webkit
The [capybara-webkit driver](https://github.com/thoughtbot/capybara-webkit) is for true headless
testing. It uses QtWebKit to start a rendering engine process. It can execute JavaScript as well.
It is significantly faster than drivers like Selenium since it does not load an entire browser.
You can install it with:
```bash
gem install capybara-webkit
```
And you can use it by:
```ruby
Capybara.javascript_driver = :webkit
```
### Poltergeist
[Poltergeist](https://github.com/jonleighton/poltergeist) is another
headless driver which integrates Capybara with
[PhantomJS](http://phantomjs.org/). It is truly headless, so doesn't
require Xvfb to run on your CI server. It will also detect and report
any Javascript errors that happen within the page.
## The DSL
*A complete reference is available at
[rubydoc.info](http://rubydoc.info/github/jnicklas/capybara/master)*.
**Note**: All searches in Capybara are *case sensitive*. This is because
Capybara heavily uses XPath, which doesn't support case insensitivity.
### Navigating
You can use the
[#visit](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Session#visit-instance_method)
method to navigate to other pages:
```ruby
visit('/projects')
visit(post_comments_path(post))
```
The visit method only takes a single parameter, the request method is **always**
GET.
You can get the [current path](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Session#current_path-instance_method)
of the browsing session for test assertions:
```ruby
current_path.should == post_comments_path(post)
```
### Clicking links and buttons
*Full reference: [Capybara::Node::Actions](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Actions)*
You can interact with the webapp by following links and buttons. Capybara
automatically follows any redirects, and submits forms associated with buttons.
```ruby
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click_on('Link Text') # clicks on either links or buttons
click_on('Button Value')
```
### Interacting with forms
*Full reference: [Capybara::Node::Actions](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Actions)*
There are a number of tools for interacting with form elements:
```ruby
fill_in('First Name', :with => 'John')
fill_in('Password', :with => 'Seekrit')
fill_in('Description', :with => 'Really Long Text...')
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
attach_file('Image', '/path/to/image.jpg')
select('Option', :from => 'Select Box')
```
### Querying
*Full reference: [Capybara::Node::Matchers](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers)*
Capybara has a rich set of options for querying the page for the existence of
certain elements, and working with and manipulating those elements.
```ruby
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')
```
**Note:** The negative forms like `has_no_selector?` are different from `not
has_selector?`. Read the section on asynchronous JavaScript for an explanation.
You can use these with RSpec's magic matchers:
```ruby
page.should have_selector('table tr')
page.should have_selector(:xpath, '//table/tr')
page.should have_xpath('//table/tr')
page.should have_css('table tr.foo')
page.should have_content('foo')
```
### Finding
_Full reference: [Capybara::Node::Finders](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Finders)_
You can also find specific elements, in order to manipulate them:
```ruby
find_field('First Name').value
find_link('Hello').visible?
find_button('Send').click
find(:xpath, "//table/tr").click
find("#overlay").find("h1").click
all('a').each { |a| a[:href] }
```
**Note**: `find` will wait for an element to appear on the page, as explained in the
Ajax section. If the element does not appear it will raise an error.
These elements all have all the Capybara DSL methods available, so you can restrict them
to specific parts of the page:
```ruby
find('#navigation').click_link('Home')
find('#navigation').should have_button('Sign out')
```
### Scoping
Capybara makes it possible to restrict certain actions, such as interacting with
forms or clicking links and buttons, to within a specific area of the page. For
this purpose you can use the generic
[within](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Session#within-instance_method)
method. Optionally you can specify which kind of selector to use.
```ruby
within("li#employee") do
fill_in 'Name', :with => 'Jimmy'
end
within(:xpath, "//li[@id='employee']") do
fill_in 'Name', :with => 'Jimmy'
end
```
**Note**: `within` will scope the actions to the _first_ (not _any_) element that matches the selector.
There are special methods for restricting the scope to a specific fieldset,
identified by either an id or the text of the fieldset's legend tag, and to a
specific table, identified by either id or text of the table's caption tag.
```ruby
within_fieldset('Employee') do
fill_in 'Name', :with => 'Jimmy'
end
within_table('Employee') do
fill_in 'Name', :with => 'Jimmy'
end
```
### Scripting
In drivers which support it, you can easily execute JavaScript:
```ruby
page.execute_script("$('body').empty()")
```
For simple expressions, you can return the result of the script. Note
that this may break with more complicated expressions:
```ruby
result = page.evaluate_script('4 + 4');
```
### Debugging
It can be useful to take a snapshot of the page as it currently is and take a
look at it:
```ruby
save_and_open_page
```
You can also retrieve the current state of the DOM as a string using
[page.html](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Session#html-instance_method).
```ruby
print page.html
```
This is mostly useful for debugging. You should avoid testing against the
contents of `page.html` and use the more expressive finder methods instead.
Finally, in drivers that support it, you can save a screenshot:
```ruby
page.save_screenshot('screenshot.png')
```
## Matching
It is possible to customize how Capybara finds elements. At your disposal
are two options, `Capybara.exact` and `Capybara.match`.
### Exactness
`Capybara.exact` and the `exact` option work together with the `is` expression
inside the XPath gem. When `exact` is true, all `is` expressions match exactly,
when it is false, they allow substring matches. Many of the selectors built into
Capybara use the `is` expression. This way you can specify whether you want to
allow substring matches or not. `Capybara.exact` is false by default.
For example:
```ruby
click_link("Password") # also matches "Password confirmation"
Capybara.exact = true
click_link("Password") # does not match "Password confirmation"
click_link("Password", exact: false) # can be overridden
```
### Strategy
Using `Capybara.match` and the equivalent `match` option, you can control how
Capybara behaves when multiple elements all match a query. There are currently
four different strategies built into Capybara:
1. **first:** Just picks the first element that matches.
2. **one:** Raises an error if more than one element matches.
3. **smart:** If `exact` is `true`, raises an error if more than one element
matches, just like `one`. If `exact` is `false`, it will first try to find
an exact match. An error is raised if more than one element is found. If no
element is found, a new search is performed which allows partial matches. If
that search returns multiple matches, an error is raised.
4. **prefer_exact:** If multiple matches are found, some of which are exact,
and some of which are not, then the first exactly matching element is
returned.
The default for `Capybara.match` is `:smart`. To emulate the behaviour in
Capybara 2.0.x, set `Capybara.match` to `:one`. To emulate the behaviour in
Capybara 1.x, set `Capybara.match` to `:prefer_exact`.
## Transactions and database setup
Some Capybara drivers need to run against an actual HTTP server. Capybara takes
care of this and starts one for you in the same process as your test, but on
another thread. Selenium is one of those drivers, whereas RackTest is not.
If you are using a SQL database, it is common to run every test in a
transaction, which is rolled back at the end of the test, rspec-rails does this
by default out of the box for example. Since transactions are usually not
shared across threads, this will cause data you have put into the database in
your test code to be invisible to Capybara.
Cucumber handles this by using truncation instead of transactions, i.e. they
empty out the entire database after each test. You can get the same behaviour
by using a gem such as [database_cleaner](https://github.com/bmabey/database_cleaner).
It is also possible to force your ORM to use the same transaction for all
threads. This may have thread safety implications and could cause strange
failures, so use caution with this approach. It can be implemented in
ActiveRecord through the following monkey patch:
```ruby
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
```
## Asynchronous JavaScript (Ajax and friends)
When working with asynchronous JavaScript, you might come across situations
where you are attempting to interact with an element which is not yet present
on the page. Capybara automatically deals with this by waiting for elements
to appear on the page.
When issuing instructions to the DSL such as:
```ruby
click_link('foo')
click_link('bar')
page.should have_content('baz')
```
If clicking on the *foo* link triggers an asynchronous process, such as
an Ajax request, which, when complete will add the *bar* link to the page,
clicking on the *bar* link would be expected to fail, since that link doesn't
exist yet. However Capybara is smart enough to retry finding the link for a
brief period of time before giving up and throwing an error. The same is true of
the next line, which looks for the content *baz* on the page; it will retry
looking for that content for a brief time. You can adjust how long this period
is (the default is 2 seconds):
```ruby
Capybara.default_wait_time = 5
```
Be aware that because of this behaviour, the following two statements are **not**
equivalent, and you should **always** use the latter!
```ruby
!page.has_xpath?('a')
page.has_no_xpath?('a')
```
The former would immediately fail because the content has not yet been removed.
Only the latter would wait for the asynchronous process to remove the content
from the page.
Capybara's Rspec matchers, however, are smart enough to handle either form.
The two following statements are functionally equivalent:
```ruby
page.should_not have_xpath('a')
page.should have_no_xpath('a')
```
Capybara's waiting behaviour is quite advanced, and can deal with situations
such as the following line of code:
```ruby
find('#sidebar').find('h1').should have_content('Something')
```
Even if JavaScript causes `#sidebar` to disappear off the page, Capybara
will automatically reload it and any elements it contains. So if an AJAX
request causes the contents of `#sidebar` to change, which would update
the text of the `h1` to "Something", and this happened, this test would
pass. If you do not want this behaviour, you can set
`Capybara.automatic_reload` to `false`.
## Using the DSL elsewhere
You can mix the DSL into any context by including Capybara::DSL:
```ruby
require 'capybara'
require 'capybara/dsl'
Capybara.default_driver = :webkit
module MyModule
include Capybara::DSL
def login!
within("//form[@id='session']") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
end
```
This enables its use in unsupported testing frameworks, and for general-purpose scripting.
## Calling remote servers
Normally Capybara expects to be testing an in-process Rack application, but you
can also use it to talk to a web server running anywhere on the internet, by
setting app_host:
```ruby
Capybara.current_driver = :selenium
Capybara.app_host = 'http://www.google.com'
...
visit('/')
```
**Note**: the default driver (`:rack_test`) does not support running
against a remote server. With drivers that support it, you can also visit any
URL directly:
```ruby
visit('http://www.google.com')
```
By default Capybara will try to boot a rack application automatically. You
might want to switch off Capybara's rack server if you are running against a
remote application:
```ruby
Capybara.run_server = false
```
## Using the sessions manually
For ultimate control, you can instantiate and use a
[Session](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Session)
manually.
```ruby
require 'capybara'
session = Capybara::Session.new(:webkit, my_rack_app)
session.within("//form[@id='session']") do
session.fill_in 'Login', :with => 'user@example.com'
session.fill_in 'Password', :with => 'password'
end
session.click_link 'Sign in'
```
## XPath, CSS and selectors
Capybara does not try to guess what kind of selector you are going to give it,
and will always use CSS by default. If you want to use XPath, you'll need to
do:
```ruby
within(:xpath, '//ul/li') { ... }
find(:xpath, '//ul/li').text
find(:xpath, '//li[contains(.//a[@href = "#"]/text(), "foo")]').value
```
Alternatively you can set the default selector to XPath:
```ruby
Capybara.default_selector = :xpath
find('//ul/li').text
```
Capybara allows you to add custom selectors, which can be very useful if you
find yourself using the same kinds of selectors very often:
```ruby
Capybara.add_selector(:id) do
xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
end
Capybara.add_selector(:row) do
xpath { |num| ".//tbody/tr[#{num}]" }
end
Capybara.add_selector(:flash_type) do
css { |type| "#flash.#{type}" }
end
```
The block given to xpath must always return an XPath expression as a String, or
an XPath expression generated through the XPath gem. You can now use these
selectors like this:
```ruby
find(:id, 'post_123')
find(:row, 3)
find(:flash_type, :notice)
```
## Beware the XPath // trap
In XPath the expression // means something very specific, and it might not be what
you think. Contrary to common belief, // means "anywhere in the document" not "anywhere
in the current context". As an example:
```ruby
page.find(:xpath, '//body').all(:xpath, '//script')
```
You might expect this to find all script tags in the body, but actually, it finds all
script tags in the entire document, not only those in the body! What you're looking
for is the .// expression which means "any descendant of the current node":
```ruby
page.find(:xpath, '//body').all(:xpath, './/script')
```
The same thing goes for within:
```ruby
within(:xpath, '//body') do
page.find(:xpath, './/script')
within(:xpath, './/table/tbody') do
...
end
end
```
## Configuring and adding drivers
Capybara makes it convenient to switch between different drivers. It also exposes
an API to tweak those drivers with whatever settings you want, or to add your own
drivers. This is how to switch the selenium driver to use chrome:
```ruby
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
```
However, it's also possible to give this a different name, so tests can switch
between using different browsers effortlessly:
```ruby
Capybara.register_driver :selenium_chrome do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
```
Whatever is returned from the block should conform to the API described by
Capybara::Driver::Base, it does not however have to inherit from this class.
Gems can use this API to add their own drivers to Capybara.
The [Selenium wiki](http://code.google.com/p/selenium/wiki/RubyBindings) has
additional info about how the underlying driver can be configured.
## Gotchas:
* Access to session and request is not possible from the test, Access to
response is limited. Some drivers allow access to response headers and HTTP
status code, but this kind of functionality is not provided by some drivers,
such as Selenium.
* Access to Rails specific stuff (such as `controller`) is unavailable,
since we're not using Rails' integration testing.
* Freezing time: It's common practice to mock out the Time so that features
that depend on the current Date work as expected. This can be problematic,
since Capybara's Ajax timing uses the system time, resulting in Capybara
never timing out and just hanging when a failure occurs. It's still possible to
use gems which allow you to travel in time, rather than freeze time.
One such gem is [Timecop](http://github.com/travisjeffery/timecop).
* When using Rack::Test, beware if attempting to visit absolute URLs. For
example, a session might not be shared between visits to `posts_path`
and `posts_url`. If testing an absolute URL in an Action Mailer email,
set `default_url_options` to match the Rails default of
`www.example.com`.
## Development
To set up a development environment, simply do:
```bash
bundle install
bundle exec rake # run the test suite
```
See
[CONTRIBUTING.md](https://github.com/jnicklas/capybara/blob/master/CONTRIBUTING.md)
for how to send issues and pull requests.
capybara-2.1.0/data.tar.gz.sig 0000644 0001750 0001750 00000000400 12140721202 015122 0 ustar lunar lunar `Z6xׄ9K"B9"2oȩ3fmEchJIBc^kLdoY%Y)#WoMnJ-jm>3U5 T\BUh
̐V
0r~:y_ԥT2c3^{~XfaF2DhI$`#<챎ԽH