Capybara is basically a library that helps you test web applications by simulating how a real user would interact with your app.
Capybara requires Ruby 1.9.3 or later. To install, type in your terminal:
Capybara tests are often called feature tests or end-to-end testing. It was built on top of Nokogiri in order to discover the elements on a page using HTML and CSS. It is a DSL (Domain Specific Language) that is built on top of and Cucumber.
Capybara tests are like RSpec tests with Capybara flavoring (yum giant rodent). Some keywords:
|Capybara DSL||RSpec DSL|
Capybara uses a web driver (in this example Selenium) to do some browser magic. It lets you control the browser through code and has the browser take actions on your behalf in order to make sure the website actually works as the user will experience. Normally a “headless browser” is used to save memory, but the example below will show it to you live…for funsies.
Examples of Capybara syntax:
|Method||What it does|
|visit ‘url’||goes to the given url|
|fill_in(locator, :with => option)||finds text field by id and fills in with option|
|click_button(locator)||finds button by id and clicks it|
Capybara with Google and Youtube Searches.
You can download this code here.
In your project folder, add Capybara and Selenium-WebDriver to your Gemfile. It should look like this:
1 2 3 4 5 6 7 8 9
Don’t forget to bundle
Create a simple_app.rb file (it got mad at me if I didn’t include this file).
1 2 3 4 5
Normally, there’d be more folders in your application, but this is a very simple example so everything is in the top level.
Your environment.rb should look like this:
1 2 3 4
And your config.ru…
1 2 3
Require Capybara in your spec_helper.rb file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Here’s what my features_spec.rb looks like. I’m using Capybara to search Google.com for “Flatiron School” and then visiting YouTube to look for cat videos. In each describe block, I tell Capybara to visit the website and fill in the text field with what I’m searching for and then click submit. The
sleep 2 is there to slow down the process so you can see it better in Step 8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
rspec in your terminal and watch it do the searches and pass the tests.