Capybara helps you test Rails and Rack 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
To install, type
sudo gem install capybara
If you are using Rails, add this line to your test helper file:
require 'capybara/rails'
If you are not using Rails, set Capybara.app to your rack app:
Capybara.app = MyRackApp
The cucumber-rails
gem comes with Capybara support built-in. If you
are not using Rails, manually load the capybara/cucumber
module:
require 'capybara/cucumber'
Capybara.app = MyRackApp
You can use the Capybara DSL in your steps, like so:
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
:
@javascript
Scenario: do something Ajaxy
When I click the Ajax link
...
There are also explicit @selenium
and @rack_test
tags set up for you.
Load RSpec 2.x support by adding the following line (typically to your
spec_helper.rb
file):
require 'capybara/rspec'
If you are using Rails, put your Capybara specs in spec/requests
or
spec/integration
.
If you are not using Rails, tag all the example groups in which you want to use
Capybara with :type => :request
.
You can now write your specs like so:
describe "the signup process", :type => :request do
before :each do
User.make(:email => 'user@example.com', :password => 'caplin')
end
it "signs me in" do
within("#session") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
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:
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:
feature "Signing up" do
background do
User.make(:email => 'user@example.com', :password => 'caplin')
end
scenario "Signing in with correct credentials" do
within("#session") do
fill_in 'Login', :with => 'user@example.com'
fill_in 'Password', :with => 'caplin'
end
click_link 'Sign in'
end
end
feature
is in fact just an alias for describe ..., :type => :request
,
background
is an alias for before
, and scenario
for it
.
-
If you are using Rails, add
database_cleaner
to your Gemfile:group :test do gem 'database_cleaner' end
Then add the following code in your
test_helper.rb
file to make Capybara available in all test cases deriving fromActionDispatch::IntegrationTest
:# Transactional fixtures do not work with Selenium tests, because Capybara # uses a separate server thread, which the transactions would be hidden # from. We hence use DatabaseCleaner to truncate our test database. DatabaseCleaner.strategy = :truncation class ActionDispatch::IntegrationTest # Make the Capybara DSL available in all integration tests include Capybara::DSL # Stop ActiveRecord from wrapping tests in transactions self.use_transactional_fixtures = false teardown do DatabaseCleaner.clean # Truncate the database Capybara.reset_sessions! # Forget the (simulated) browser state Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver end end
-
If you are not using Rails, define a base class for your Capybara tests like so:
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 overrideteardown
.
To switch the driver, set Capybara.current_driver
. For instance,
class BlogTest < ActionDispatch::IntegrationTest
setup do
Capybara.current_driver = Capybara.javascript_driver # :selenium by default
end
test 'shows blog posts'
# ... this test is run with Selenium ...
end
end
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, rubygems.org) provides MiniTest::Spec expectations for Capybara. For example:
page.must_have_content('Important!')
Capybara uses the same DSL to drive a variety of browser and headless drivers.
By default, Capybara uses the :rack_test
driver, which is fast but does not
support JavaScript. 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:
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):
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 is Capybara's default driver. It is written in pure Ruby and does not have any support for executing JavaScript. Since the RackTest driver works directly against the Rack interface, it does not need any server to be started, it can work directly work against any Rack app. 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. You cannot use the RackTest driver to test a remote application. capybara-mechanize intends to provide a similar driver which works against remote servers, it is a separate project.
RackTest can be configured with a set of headers like this:
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app, :browser => :chrome)
end
See the section on adding and configuring drivers.
At the moment, Capybara supports Selenium 2.0 (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.
Capybara can block and wait for Ajax requests to finish after you've interacted
with the page. To enable this behaviour, set the :resynchronize
driver
option to true
. This should normally not be necessary, since
Capybara's automatic reloading should take care of any asynchronicity problems.
See the section on Asynchronous JavaScript for details.
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.
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.
You can install it with:
gem install capybara-webkit
And you can use it by:
Capybara.javascript_driver = :webkit
A complete reference is available at at rubydoc.info.
Note: All searches in Capybara are case sensitive. This is because Capybara heavily uses XPath, which doesn't support case insensitivity.
You can use the #visit method to navigate to other pages:
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 of the browsing session for test assertions:
current_path.should == post_comments_path(post)
Full reference: 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.
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')
Full reference: Capybara::Node::Actions
There are a number of tools for interacting with form elements:
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')
Full reference: 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.
page.has_selector?('table tr')
page.has_selector?(:xpath, '//table/tr')
page.has_no_selector?(:content)
page.has_xpath?('//table/tr')
page.has_css?('table tr.foo')
page.has_text?('foo') # synonymously: 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:
page.should have_selector('table tr')
page.should have_selector(:xpath, '//table/tr')
page.should have_no_selector(:content)
page.should have_xpath('//table/tr')
page.should have_css('table tr.foo')
page.should have_text('foo')
If all else fails, you can also use the page.html method to test against the raw HTML:
page.html.should match /<span>.../i
Full reference: Capybara::Node::Finders
You can also find specific elements, in order to manipulate them:
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:
find('#navigation').click_link('Home')
find('#navigation').should have_button('Sign out')
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.
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 fieldet's legend tag, and to a specific table, identified by either id or text of the table's caption tag.
within_fieldset('Employee') do
fill_in 'Name', :with => 'Jimmy'
end
within_table('Employee') do
fill_in 'Name', :with => 'Jimmy'
end
In drivers which support it, you can easily execute JavaScript:
page.execute_script("$('body').empty()")