So far, we've come across more than a few built-in Capybara matchers.
Each of them follow with the standard format of
expect(page).to have something such as CSS, xpath, content, text, a link, to have a field, a checked field, an unchecked field, a button, a table, or a selector.
:::tip Checking for Absence of Elements Yes, it is possible to actually check that the page doesn't have a certain CSS selector, or doesn't have a link, or doesn't have a particular button. The problem is that if you do a negative assertion, something like checking there isn't a button, you might be adding lag to our tests since we might be waiting quite some time to confirm that the element does not load. :::
Remember, for this particular project, we've set, as a Capybara property, the max wait time to be ten whole seconds, so asserting that an element's actually on the page might be a faster test.
Let's check out the official documentation.
Going to Team Capybara's GitHub site, we can scroll down to the section talking about matching. We can match by exactness and by strategy.
If you take a look, you can find that there's very interesting properties you can set with each Capybara matchers.
Each of these matchers has various options you can use.
There's also various strategies.
Let's say there's 2 links on a page: “Password” and “Password Confirmation”.
have_link("Password") is going to match both entries
have_link("Password") and use the options of exact true —
have_link("Password", exact: true) — it's only going to match the first entry because we're just searching for the link that only has the word password in it and not password confirmation
By definition, Capybara's
exact property is false. You can set it to be true for the entire project in the
spec_helper or just for that one match, as in the example we just mentioned.
Capybara also has different strategies to handle duplicate matches.
first, where it just picks the first element that matches
one, which raises an error if more than one element matches
smart, which is actually the default for Capybara, which will throw an error if more than one element matches
prefer_exact, which will search for the first exactly matching element that's returned
Some examples — let's say you want to match the link password.
You could match the
::: Read the Capybara README If you really want to know what Matchers — or any other part of Capybara — can do, your primary resource should always be the documentation posted on Team Capybara's GitHub. :::