{"id":8058,"date":"2022-08-30T15:15:02","date_gmt":"2022-08-30T15:15:02","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/11\/23\/jnicklas-capybara\/"},"modified":"2022-08-30T15:39:09","modified_gmt":"2022-08-30T15:39:09","slug":"jnicklas-capybara","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/jnicklas-capybara\/","title":{"rendered":"jnicklas\/capybara"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/secure.travis-ci.org\/jnicklas\/capybara.png\" \/> \u00a0<img decoding=\"async\" src=\"http:\/\/codeclimate.com\/github\/jnicklas\/capybara.png\" \/><\/p>\n<p>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.<\/p>\n<p><strong>Need help?<\/strong> Ask on the mailing list (please do not open an issue on GitHub): http:\/\/groups.google.com\/group\/ruby-capybara<\/p>\n<h2>Table of contents<\/h2>\n<h2>Key benefits<\/h2>\n<ul>\n<li><strong>No setup<\/strong> necessary for Rails and Rack application. Works out of the box.<\/li>\n<li><strong>Intuitive API<\/strong> which mimics the language an actual user would use.<\/li>\n<li><strong>Switch the backend<\/strong> your tests run against from fast headless mode to an actual browser with no changes to your tests.<\/li>\n<li><strong>Powerful synchronization<\/strong> features mean you never have to manually wait for asynchronous processes to complete.<\/li>\n<\/ul>\n<h2>Setup<\/h2>\n<p>Capybara requires Ruby 1.9.3 or later. To install, add this line to your <code>Gemfile<\/code> and run <code>bundle install<\/code>:<\/p>\n<pre><code>gem 'capybara'\n<\/code><\/pre>\n<p>If the application that you are testing is a Rails app, add this line to your test helper file:<\/p>\n<pre><code>require 'capybara\/rails'\n<\/code><\/pre>\n<p><strong>Note:<\/strong> In Rails 4.0\/4.1 the default test environment (<code>config\/environments\/test.rb<\/code>) is not threadsafe. If you experience random errors about missing constants, add <code>config.allow_concurrency = false<\/code> to <code>config\/environments\/test.rb<\/code>.<\/p>\n<p>If the application that you are testing is a Rack app, but not Rails, set Capybara.app to your Rack app:<\/p>\n<pre><code>Capybara.app = MyRackApp\n<\/code><\/pre>\n<p>If you need to test JavaScript, or if your app interacts with (or is located at) a remote URL, you\u2019ll need to use a different driver.<\/p>\n<h2>Using Capybara with Cucumber<\/h2>\n<p>The <code>cucumber-rails<\/code> gem comes with Capybara support built-in. If you are not using Rails, manually load the <code>capybara\/cucumber<\/code> module:<\/p>\n<pre><code>require 'capybara\/cucumber'\nCapybara.app = MyRackApp\n<\/code><\/pre>\n<p>You can use the Capybara DSL in your steps, like so:<\/p>\n<pre><code>When \/I sign in\/ do\n  within(\"#session\") do\n    fill_in 'Email', :with =&gt; 'user@example.com'\n    fill_in 'Password', :with =&gt; 'password'\n  end\n  click_button 'Sign in'\nend\n<\/code><\/pre>\n<p>You can switch to the <code>Capybara.javascript_driver<\/code> (<code>:selenium<\/code> by default) by tagging scenarios (or features) with <code>@javascript<\/code>:<\/p>\n<pre><code>@javascript\nScenario: do something Ajaxy\n  When I click the Ajax link\n  ...\n<\/code><\/pre>\n<p>There are also explicit <code>@selenium<\/code> and <code>@rack_test<\/code> tags set up for you.<\/p>\n<h2>Using Capybara with RSpec<\/h2>\n<p>Load RSpec 2.x support by adding the following line (typically to your <code>spec_helper.rb<\/code> file):<\/p>\n<pre><code>require 'capybara\/rspec'\n<\/code><\/pre>\n<p>If you are using Rails, put your Capybara specs in <code>spec\/features<\/code>.<\/p>\n<p>If you are not using Rails, tag all the example groups in which you want to use Capybara with <code>:type =&gt; :feature<\/code>.<\/p>\n<p>You can now write your specs like so:<\/p>\n<pre><code>describe \"the signin process\", :type =&gt; :feature do\n  before :each do\n    User.make(:email =&gt; 'user@example.com', :password =&gt; 'password')\n  end\n\n  it \"signs me in\" do\n    visit '\/sessions\/new'\n    within(\"#session\") do\n      fill_in 'Email', :with =&gt; 'user@example.com'\n      fill_in 'Password', :with =&gt; 'password'\n    end\n    click_button 'Sign in'\n    expect(page).to have_content 'Success'\n  end\nend\n<\/code><\/pre>\n<p>Use <code>:js =&gt; true<\/code> to switch to the <code>Capybara.javascript_driver<\/code> (<code>:selenium<\/code> by default), or provide a <code>:driver<\/code> option to switch to one specific driver. For example:<\/p>\n<pre><code>describe 'some stuff which requires js', :js =&gt; true do\n  it 'will use the default js driver'\n  it 'will switch to one specific driver', :driver =&gt; :webkit\nend\n<\/code><\/pre>\n<p>Finally, Capybara also comes with a built in DSL for creating descriptive acceptance tests:<\/p>\n<pre><code>feature \"Signing in\" do\n  background do\n    User.make(:email =&gt; 'user@example.com', :password =&gt; 'caplin')\n  end\n\n  scenario \"Signing in with correct credentials\" do\n    visit '\/sessions\/new'\n    within(\"#session\") do\n      fill_in 'Email', :with =&gt; 'user@example.com'\n      fill_in 'Password', :with =&gt; 'caplin'\n    end\n    click_button 'Sign in'\n    expect(page).to have_content 'Success'\n  end\n\n  given(:other_user) { User.make(:email =&gt; 'other@example.com', :password =&gt; 'rous') }\n\n  scenario \"Signing in as another user\" do\n    visit '\/sessions\/new'\n    within(\"#session\") do\n      fill_in 'Email', :with =&gt; other_user.email\n      fill_in 'Password', :with =&gt; other_user.password\n    end\n    click_button 'Sign in'\n    expect(page).to have_content 'Invalid email or password'\n  end\nend\n<\/code><\/pre>\n<p><code>feature<\/code> is in fact just an alias for <code>describe ..., :type =&gt; :feature<\/code>, <code>background<\/code> is an alias for <code>before<\/code>, <code>scenario<\/code> for <code>it<\/code>, and <code>given<\/code>\/<code>given!<\/code> aliases for <code>let<\/code>\/<code>let!<\/code>, respectively.<\/p>\n<h2>Using Capybara with Test::Unit<\/h2>\n<ul>\n<li>If you are using Rails, add the following code in your <code>test_helper.rb<\/code> file to make Capybara available in all test cases deriving from <code>ActionDispatch::IntegrationTest<\/code>:\n<pre><code>class ActionDispatch::IntegrationTest\n  # Make the Capybara DSL available in all integration tests\n  include Capybara::DSL\nend\n<\/code><\/pre>\n<\/li>\n<li>If you are not using Rails, define a base class for your Capybara tests like so:\n<pre><code>class CapybaraTestCase &lt; Test::Unit::TestCase\n  include Capybara::DSL\n\n  def teardown\n    Capybara.reset_sessions!\n    Capybara.use_default_driver\n  end\nend\n<\/code><\/pre>\n<p>Remember to call <code>super<\/code> in any subclasses that override <code>teardown<\/code>.<\/li>\n<\/ul>\n<p>To switch the driver, set <code>Capybara.current_driver<\/code>. For instance,<\/p>\n<pre><code>class BlogTest &lt; ActionDispatch::IntegrationTest\n  setup do\n    Capybara.current_driver = Capybara.javascript_driver # :selenium by default\n  end\n\n  test 'shows blog posts' do\n    # ... this test is run with Selenium ...\n  end\nend\n<\/code><\/pre>\n<h2>Using Capybara with MiniTest::Spec<\/h2>\n<p>Set up your base class as with Test::Unit. (On Rails, the right base class could be something other than ActionDispatch::IntegrationTest.)<\/p>\n<p>The capybara_minitest_spec gem (GitHub, rubygems.org) provides MiniTest::Spec expectations for Capybara. For example:<\/p>\n<pre><code>page.must_have_content('Important!')\n<\/code><\/pre>\n<h2>Drivers<\/h2>\n<p>Capybara uses the same DSL to drive a variety of browser and headless drivers.<\/p>\n<h3>Selecting the Driver<\/h3>\n<p>By default, Capybara uses the <code>:rack_test<\/code> 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\u2019d prefer to run everything in Selenium, you could do:<\/p>\n<pre><code>Capybara.default_driver = :selenium\n<\/code><\/pre>\n<p>However, if you are using RSpec or Cucumber, you may instead want to consider leaving the faster <code>:rack_test<\/code> as the <strong>default_driver<\/strong>, and marking only those tests that require a JavaScript-capable driver using <code>:js =&gt; true<\/code> or <code>@javascript<\/code>, respectively. By default, JavaScript tests are run using the <code>:selenium<\/code> driver. You can change this by setting <code>Capybara.javascript_driver<\/code>.<\/p>\n<p>You can also change the driver temporarily (typically in the Before\/setup and After\/teardown blocks):<\/p>\n<pre><code>Capybara.current_driver = :webkit # temporarily select different driver\n... tests ...\nCapybara.use_default_driver       # switch back to default driver\n<\/code><\/pre>\n<p><strong>Note<\/strong>: switching the driver creates a new session, so you may not be able to switch in the middle of a test.<\/p>\n<h3>RackTest<\/h3>\n<p>RackTest is Capybara\u2019s 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.<\/p>\n<p>capybara-mechanize provides a similar driver that can access remote servers.<\/p>\n<p>RackTest can be configured with a set of headers like this:<\/p>\n<pre><code>Capybara.register_driver :rack_test do |app|\n  Capybara::RackTest::Driver.new(app, :headers =&gt; { 'HTTP_USER_AGENT' =&gt; 'Capybara' })\nend\n<\/code><\/pre>\n<p>See the section on adding and configuring drivers.<\/p>\n<h3>Selenium<\/h3>\n<p>At the moment, Capybara supports Selenium 2.0 (Webdriver), <em>not<\/em> Selenium RC. In order to use Selenium, you\u2019ll need to install the <code>selenium-webdriver<\/code> gem, and add it to your Gemfile if you\u2019re using bundler. Provided Firefox is installed, everything is set up for you, and you should be able to start using Selenium right away.<\/p>\n<p><strong>Note<\/strong>: drivers which run the server in a different thread may not share the same transaction as your tests, causing data not to be shared between your test and test server, see \u201cTransactions and database setup\u201d below.<\/p>\n<h3>Capybara-webkit<\/h3>\n<p>The capybara-webkit driver 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.<\/p>\n<p>You can install it with:<\/p>\n<pre><code>gem install capybara-webkit\n<\/code><\/pre>\n<p>And you can use it by:<\/p>\n<pre><code>Capybara.javascript_driver = :webkit\n<\/code><\/pre>\n<h3>Poltergeist<\/h3>\n<p>Poltergeist is another headless driver which integrates Capybara with PhantomJS. It is truly headless, so doesn\u2019t require Xvfb to run on your CI server. It will also detect and report any Javascript errors that happen within the page.<\/p>\n<h2>The DSL<\/h2>\n<p><em>A complete reference is available at rubydoc.info<\/em>.<\/p>\n<p><strong>Note<\/strong>: All searches in Capybara are <em>case sensitive<\/em>. This is because Capybara heavily uses XPath, which doesn\u2019t support case insensitivity.<\/p>\n<h3>Navigating<\/h3>\n<p>You can use the visit method to navigate to other pages:<\/p>\n<pre><code>visit('\/projects')\nvisit(post_comments_path(post))\n<\/code><\/pre>\n<p>The visit method only takes a single parameter, the request method is <strong>always<\/strong> GET.<\/p>\n<p>You can get the current path of the browsing session for test assertions:<\/p>\n<pre><code>expect(current_path).to eq(post_comments_path(post))\n<\/code><\/pre>\n<h3>Clicking links and buttons<\/h3>\n<p><em>Full reference: Capybara::Node::Actions<\/em><\/p>\n<p>You can interact with the webapp by following links and buttons. Capybara automatically follows any redirects, and submits forms associated with buttons.<\/p>\n<pre><code>click_link('id-of-link')\nclick_link('Link Text')\nclick_button('Save')\nclick_on('Link Text') # clicks on either links or buttons\nclick_on('Button Value')\n<\/code><\/pre>\n<h3>Interacting with forms<\/h3>\n<p><em>Full reference: Capybara::Node::Actions<\/em><\/p>\n<p>There are a number of tools for interacting with form elements:<\/p>\n<pre><code>fill_in('First Name', :with =&gt; 'John')\nfill_in('Password', :with =&gt; 'Seekrit')\nfill_in('Description', :with =&gt; 'Really Long Text...')\nchoose('A Radio Button')\ncheck('A Checkbox')\nuncheck('A Checkbox')\nattach_file('Image', '\/path\/to\/image.jpg')\nselect('Option', :from =&gt; 'Select Box')\n<\/code><\/pre>\n<h3>Querying<\/h3>\n<p><em>Full reference: Capybara::Node::Matchers<\/em><\/p>\n<p>Capybara has a rich set of options for querying the page for the existence of certain elements, and working with and manipulating those elements.<\/p>\n<pre><code>page.has_selector?('table tr')\npage.has_selector?(:xpath, '\/\/table\/tr')\n\npage.has_xpath?('\/\/table\/tr')\npage.has_css?('table tr.foo')\npage.has_content?('foo')\n<\/code><\/pre>\n<p><strong>Note:<\/strong> The negative forms like <code>has_no_selector?<\/code> are different from <code>not has_selector?<\/code>. Read the section on asynchronous JavaScript for an explanation.<\/p>\n<p>You can use these with RSpec\u2019s magic matchers:<\/p>\n<pre><code>expect(page).to have_selector('table tr')\nexpect(page).to have_selector(:xpath, '\/\/table\/tr')\n\nexpect(page).to have_xpath('\/\/table\/tr')\nexpect(page).to have_css('table tr.foo')\nexpect(page).to have_content('foo')\n<\/code><\/pre>\n<h3>Finding<\/h3>\n<p><em>Full reference: Capybara::Node::Finders<\/em><\/p>\n<p>You can also find specific elements, in order to manipulate them:<\/p>\n<pre><code>find_field('First Name').value\nfind_link('Hello').visible?\nfind_button('Send').click\n\nfind(:xpath, \"\/\/table\/tr\").click\nfind(\"#overlay\").find(\"h1\").click\nall('a').each { |a| a[:href] }\n<\/code><\/pre>\n<p><strong>Note<\/strong>: <code>find<\/code> 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.<\/p>\n<p>These elements all have all the Capybara DSL methods available, so you can restrict them to specific parts of the page:<\/p>\n<pre><code>find('#navigation').click_link('Home')\nexpect(find('#navigation')).to have_button('Sign out')\n<\/code><\/pre>\n<h3>Scoping<\/h3>\n<p>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 method. Optionally you can specify which kind of selector to use.<\/p>\n<pre><code>within(\"li#employee\") do\n  fill_in 'Name', :with =&gt; 'Jimmy'\nend\n\nwithin(:xpath, \"\/\/li[@id='employee']\") do\n  fill_in 'Name', :with =&gt; 'Jimmy'\nend\n<\/code><\/pre>\n<p>There are special methods for restricting the scope to a specific fieldset, identified by either an id or the text of the fieldset\u2019s legend tag, and to a specific table, identified by either id or text of the table\u2019s caption tag.<\/p>\n<pre><code>within_fieldset('Employee') do\n  fill_in 'Name', :with =&gt; 'Jimmy'\nend\n\nwithin_table('Employee') do\n  fill_in 'Name', :with =&gt; 'Jimmy'\nend\n<\/code><\/pre>\n<h3>Working with windows<\/h3>\n<p>Capybara provides some methods to ease finding and switching windows:<\/p>\n<pre><code>facebook_window = window_opened_by do\n  click_button 'Like'\nend\nwithin_window facebook_window do\n  find('#login_email').set('a@example.com')\n  find('#login_password').set('qwerty')\n  click_button 'Submit'\nend\n<\/code><\/pre>\n<h3>Scripting<\/h3>\n<p>In drivers which support it, you can easily execute JavaScript:<\/p>\n<pre><code>page.execute_script(\"$('body').empty()\")\n<\/code><\/pre>\n<p>For simple expressions, you can return the result of the script. Note that this may break with more complicated expressions:<\/p>\n<pre><code>result = page.evaluate_script('4 + 4');\n<\/code><\/pre>\n<h3>Modals<\/h3>\n<p>In drivers which support it, you can accept, dismiss and respond to alerts, confirms and prompts.<\/p>\n<p>You can accept or dismiss alert messages by wrapping the code that produces an alert in a block:<\/p>\n<pre><code>accept_alert do\n  click_link('Show Alert')\nend\n<\/code><\/pre>\n<p>You can accept or dismiss a confirmation by wrapping it in a block, as well:<\/p>\n<pre><code>dismiss_confirm do\n  click_link('Show Confirm')\nend\n<\/code><\/pre>\n<p>You can accept or dismiss prompts as well, and also provide text to fill in for the response:<\/p>\n<pre><code>accept_prompt(with: 'Linus Torvalds') do\n  click_link('Show Prompt About Linux')\nend\n<\/code><\/pre>\n<p>All modal methods return the message that was presented. So, you can access the prompt message by assigning the return to a variable:<\/p>\n<pre><code>message = accept_prompt(with: 'Linus Torvalds') do\n  click_link('Show Prompt About Linux')\nend\nexpect(message).to eq('Who is the chief architect of Linux?')\n<\/code><\/pre>\n<h3>Debugging<\/h3>\n<p>It can be useful to take a snapshot of the page as it currently is and take a look at it:<\/p>\n<pre><code>save_and_open_page\n<\/code><\/pre>\n<p>You can also retrieve the current state of the DOM as a string using page.html.<\/p>\n<pre><code>print page.html\n<\/code><\/pre>\n<p>This is mostly useful for debugging. You should avoid testing against the contents of <code>page.html<\/code> and use the more expressive finder methods instead.<\/p>\n<p>Finally, in drivers that support it, you can save a screenshot:<\/p>\n<pre><code>page.save_screenshot('screenshot.png')\n<\/code><\/pre>\n<p>Or have it save and automatically open:<\/p>\n<pre><code>save_and_open_screenshot\n<\/code><\/pre>\n<h2>Matching<\/h2>\n<p>It is possible to customize how Capybara finds elements. At your disposal are two options, <code>Capybara.exact<\/code> and <code>Capybara.match<\/code>.<\/p>\n<h3>Exactness<\/h3>\n<p><code>Capybara.exact<\/code> and the <code>exact<\/code> option work together with the <code>is<\/code> expression inside the XPath gem. When <code>exact<\/code> is true, all <code>is<\/code> expressions match exactly, when it is false, they allow substring matches. Many of the selectors built into Capybara use the <code>is<\/code> expression. This way you can specify whether you want to allow substring matches or not. <code>Capybara.exact<\/code> is false by default.<\/p>\n<p>For example:<\/p>\n<pre><code>click_link(\"Password\") # also matches \"Password confirmation\"\nCapybara.exact = true\nclick_link(\"Password\") # does not match \"Password confirmation\"\nclick_link(\"Password\", exact: false) # can be overridden\n<\/code><\/pre>\n<h3>Strategy<\/h3>\n<p>Using <code>Capybara.match<\/code> and the equivalent <code>match<\/code> option, you can control how Capybara behaves when multiple elements all match a query. There are currently four different strategies built into Capybara:<\/p>\n<ol>\n<li><strong>first:<\/strong> Just picks the first element that matches.<\/li>\n<li><strong>one:<\/strong> Raises an error if more than one element matches.<\/li>\n<li><strong>smart:<\/strong> If <code>exact<\/code> is <code>true<\/code>, raises an error if more than one element matches, just like <code>one<\/code>. If <code>exact<\/code> is <code>false<\/code>, 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.<\/li>\n<li><strong>prefer_exact:<\/strong> If multiple matches are found, some of which are exact, and some of which are not, then the first exactly matching element is returned.<\/li>\n<\/ol>\n<p>The default for <code>Capybara.match<\/code> is <code>:smart<\/code>. To emulate the behaviour in Capybara 2.0.x, set <code>Capybara.match<\/code> to <code>:one<\/code>. To emulate the behaviour in Capybara 1.x, set <code>Capybara.match<\/code> to <code>:prefer_exact<\/code>.<\/p>\n<h2>Transactions and database setup<\/h2>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>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:<\/p>\n<pre><code>class ActiveRecord::Base\n  mattr_accessor :shared_connection\n  @@shared_connection = nil\n\n  def self.connection\n    @@shared_connection || retrieve_connection\n  end\nend\nActiveRecord::Base.shared_connection = ActiveRecord::Base.connection\n<\/code><\/pre>\n<h2>Asynchronous JavaScript (Ajax and friends)<\/h2>\n<p>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.<\/p>\n<p>When issuing instructions to the DSL such as:<\/p>\n<pre><code>click_link('foo')\nclick_link('bar')\nexpect(page).to have_content('baz')\n<\/code><\/pre>\n<p>If clicking on the <em>foo<\/em> link triggers an asynchronous process, such as an Ajax request, which, when complete will add the <em>bar<\/em> link to the page, clicking on the <em>bar<\/em> link would be expected to fail, since that link doesn\u2019t 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 <em>baz<\/em> 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):<\/p>\n<pre><code>Capybara.default_max_wait_time = 5\n<\/code><\/pre>\n<p>Be aware that because of this behaviour, the following two statements are <strong>not<\/strong> equivalent, and you should <strong>always<\/strong> use the latter!<\/p>\n<pre><code>!page.has_xpath?('a')\npage.has_no_xpath?('a')\n<\/code><\/pre>\n<p>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.<\/p>\n<p>Capybara\u2019s Rspec matchers, however, are smart enough to handle either form. The two following statements are functionally equivalent:<\/p>\n<pre><code>expect(page).not_to have_xpath('a')\nexpect(page).to have_no_xpath('a')\n<\/code><\/pre>\n<p>Capybara\u2019s waiting behaviour is quite advanced, and can deal with situations such as the following line of code:<\/p>\n<pre><code>expect(find('#sidebar').find('h1')).to have_content('Something')\n<\/code><\/pre>\n<p>Even if JavaScript causes <code>#sidebar<\/code> to disappear off the page, Capybara will automatically reload it and any elements it contains. So if an AJAX request causes the contents of <code>#sidebar<\/code> to change, which would update the text of the <code>h1<\/code> to \u201cSomething\u201d, and this happened, this test would pass. If you do not want this behaviour, you can set <code>Capybara.automatic_reload<\/code> to <code>false<\/code>.<\/p>\n<h2>Using the DSL elsewhere<\/h2>\n<p>You can mix the DSL into any context by including Capybara::DSL:<\/p>\n<pre><code>require 'capybara'\nrequire 'capybara\/dsl'\n\nCapybara.default_driver = :webkit\n\nmodule MyModule\n  include Capybara::DSL\n\n  def login!\n    within(\"\/\/form[@id='session']\") do\n      fill_in 'Email', :with =&gt; 'user@example.com'\n      fill_in 'Password', :with =&gt; 'password'\n    end\n    click_button 'Sign in'\n  end\nend\n<\/code><\/pre>\n<p>This enables its use in unsupported testing frameworks, and for general-purpose scripting.<\/p>\n<h2>Calling remote servers<\/h2>\n<p>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:<\/p>\n<pre><code>Capybara.current_driver = :selenium\nCapybara.app_host = 'http:\/\/www.google.com'\n...\nvisit('\/')\n<\/code><\/pre>\n<p><strong>Note<\/strong>: the default driver (<code>:rack_test<\/code>) does not support running against a remote server. With drivers that support it, you can also visit any URL directly:<\/p>\n<pre><code>visit('http:\/\/www.google.com')\n<\/code><\/pre>\n<p>By default Capybara will try to boot a rack application automatically. You might want to switch off Capybara\u2019s rack server if you are running against a remote application:<\/p>\n<pre><code>Capybara.run_server = false\n<\/code><\/pre>\n<h2>Using the sessions manually<\/h2>\n<p>For ultimate control, you can instantiate and use a Session manually.<\/p>\n<pre><code>require 'capybara'\n\nsession = Capybara::Session.new(:webkit, my_rack_app)\nsession.within(\"\/\/form[@id='session']\") do\n  session.fill_in 'Email', :with =&gt; 'user@example.com'\n  session.fill_in 'Password', :with =&gt; 'password'\nend\nsession.click_button 'Sign in'\n<\/code><\/pre>\n<h2>XPath, CSS and selectors<\/h2>\n<p>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\u2019ll need to do:<\/p>\n<pre><code>within(:xpath, '\/\/ul\/li') { ... }\nfind(:xpath, '\/\/ul\/li').text\nfind(:xpath, '\/\/li[contains(.\/\/a[@href = \"#\"]\/text(), \"foo\")]').value\n<\/code><\/pre>\n<p>Alternatively you can set the default selector to XPath:<\/p>\n<pre><code>Capybara.default_selector = :xpath\nfind('\/\/ul\/li').text\n<\/code><\/pre>\n<p>Capybara allows you to add custom selectors, which can be very useful if you find yourself using the same kinds of selectors very often:<\/p>\n<pre><code>Capybara.add_selector(:id) do\n  xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }\nend\n\nCapybara.add_selector(:row) do\n  xpath { |num| \".\/\/tbody\/tr[#{num}]\" }\nend\n\nCapybara.add_selector(:flash_type) do\n  css { |type| \"#flash.#{type}\" }\nend\n<\/code><\/pre>\n<p>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:<\/p>\n<pre><code>find(:id, 'post_123')\nfind(:row, 3)\nfind(:flash_type, :notice)\n<\/code><\/pre>\n<h2>Beware the XPath \/\/ trap<\/h2>\n<p>In XPath the expression \/\/ means something very specific, and it might not be what you think. Contrary to common belief, \/\/ means \u201canywhere in the document\u201d not \u201canywhere in the current context\u201d. As an example:<\/p>\n<pre><code>page.find(:xpath, '\/\/body').all(:xpath, '\/\/script')\n<\/code><\/pre>\n<p>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\u2019re looking for is the .\/\/ expression which means \u201cany descendant of the current node\u201d:<\/p>\n<pre><code>page.find(:xpath, '\/\/body').all(:xpath, '.\/\/script')\n<\/code><\/pre>\n<p>The same thing goes for within:<\/p>\n<pre><code>within(:xpath, '\/\/body') do\n  page.find(:xpath, '.\/\/script')\n  within(:xpath, '.\/\/table\/tbody') do\n  ...\n  end\nend\n<\/code><\/pre>\n<h2>Configuring and adding drivers<\/h2>\n<p>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 override the selenium driver configuration to use chrome:<\/p>\n<pre><code>Capybara.register_driver :selenium do |app|\n  Capybara::Selenium::Driver.new(app, :browser =&gt; :chrome)\nend\n<\/code><\/pre>\n<p>However, it\u2019s also possible to give this configuration a different name.<\/p>\n<pre><code>Capybara.register_driver :selenium_chrome do |app|\n  Capybara::Selenium::Driver.new(app, :browser =&gt; :chrome)\nend\n<\/code><\/pre>\n<p>Then tests can switch between using different browsers effortlessly:<\/p>\n<pre><code>Capybara.current_driver = :selenium_chrome\n<\/code><\/pre>\n<p>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.<\/p>\n<p>The Selenium wiki has additional info about how the underlying driver can be configured.<\/p>\n<h2>Gotchas:<\/h2>\n<ul>\n<li>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.<\/li>\n<li>Access to Rails specific stuff (such as <code>controller<\/code>) is unavailable, since we\u2019re not using Rails\u2019 integration testing.<\/li>\n<li>Freezing time: It\u2019s common practice to mock out the Time so that features that depend on the current Date work as expected. This can be problematic on ruby\/platform combinations that don\u2019t support access to a monotonic process clock, since Capybara\u2019s Ajax timing uses the system time, resulting in Capybara never timing out and just hanging when a failure occurs. It\u2019s still possible to use gems which allow you to travel in time, rather than freeze time. One such gem is Timecop.<\/li>\n<li>When using Rack::Test, beware if attempting to visit absolute URLs. For example, a session might not be shared between visits to <code>posts_path<\/code> and <code>posts_url<\/code>. If testing an absolute URL in an Action Mailer email, set <code>default_url_options<\/code> to match the Rails default of <code>www.example.com<\/code>.<\/li>\n<\/ul>\n<h2>Development<\/h2>\n<p>To set up a development environment, simply do:<\/p>\n<pre><code>bundle install\nbundle exec rake  # run the test suite\n<\/code><\/pre>\n<p>See CONTRIBUTING.md for how to send issues and pull requests.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u00a0 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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-8058","post","type-post","status-publish","format-standard","hentry","category-capybara"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8058","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=8058"}],"version-history":[{"count":4,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8058\/revisions"}],"predecessor-version":[{"id":8743,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8058\/revisions\/8743"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=8058"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=8058"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=8058"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}