Capybara Webkit or Selenium or Watir to Simulate Browser Behavior
Sometimes we want to simulate browser behavior. The situation can be test or automation script.
1 2 3
using capybara dsl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
It can be useful to take a snapshot of the page as it currently is and take a look at it:
You can also retrieve the current state of the DOM as a string using page.html.
This is mostly useful for debugging. You should avoid testing against the
page.html and use the more expressive finder methods instead.
Finally, in drivers that support it, you can save a screenshot:
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 internets, by setting app_host:
1 2 3 4
Note: the default driver (
:rack_test) does not support running
against a remote server. With drivers that support it, you can also visit any
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:
Using the sessions manually
For ultimate control, you can instantiate and use a Session manually.
1 2 3 4 5 6 7 8
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:
1 2 3
Alternatively you can set the default selector to XPath:
Capybara allows you to add custom selectors, which can be very useful if you find yourself using the same kinds of selectors very often:
1 2 3 4 5 6 7 8 9 10 11
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:
1 2 3
You can specify an optional match option which will automatically use the selector if it matches the argument:
1 2 3 4
Now use it like this:
This :id selector is already built into Capybara by default, so you don’t need to add it yourself.