Capybara with Rack::Test
Capybara
Capybara is a web-based automation framework that creates certain functional tests to simulate how a user may interact with the application; it is a library used on top of a web-based driver.
RackTest
Capybara performs RackTest on applications by default since it is part of Capybara’s default drivers. These test cases are written in the Ruby programming language and simulate how a real user would use the application by interacting with it from a rack level. The test cases simulate users clicking links, filling in forms, selecting items, clicking buttons, and so on. They are run against the application, resulting in HTML data provided to Capybara and RSpec for examination.
Advantages
Using RackTest for integration testing has the following advantages:
Rack::Testis completely headless.- It uses Unix utilities instead of a real browser.
- Increased running and processing speed.
- Server does need to be used as the RackTest driver as it directly interacts with the Rack interface.
Disadvantages
Using Capybara for integration testing also has its caveats.
- It does not process JavaScript.
- If an application is not a Rack application (such as Rails and Sinatra), this driver becomes incompatible.
- Remote applications and remote URLs cannot be tested using the RackTest driver.
- There’s no GUI to render, no images to process, etc.
Capybara setup
To use the library, the following steps need to be followed:
-
Add
gem capybarato the:testand:developmentgroups in your Gemfile. -
Type
bundlein the terminal. -
Then, a set of headers (shown below) is needed to configure RackTest:
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app, headers: { 'HTTP_USER_AGENT' => 'Capybara' })
end
Examples of testing with Capybara
The examples below demonstrate some commonly used methods included in Capybara's RSpec integration.
The visit method
The visit method fetches the page whose address is given as a parameter and simulates a user navigating to that page (by clicking a hyper-link or manually typing the URL).
visit "/items/"
The current_path method
The current_path method returns the current page's path without additional URL elements such as the port, server, and protocol being used.
page.current_path
The save_and_open method
The save_and_open method stores all the information on the current page in a file (as static HTML), which is automatically opened in the browser. This method is a great debugging tool in case a test case doesn't perform as it would be expected to.
save_and_open_page
The within method
The within method targets a specific section or component on the page. This allows certain components to be tested in isolation.
within("#items") do...something...end
Conclusion
With feature/integration tests like the ones described above, Capybara allows seamless application testing from a user's perspective, and the automation significantly helps speed up this process.
Free Resources