Capybara -RSpec Matchers

Capybara

svg viewer

Capybara is a web-based automation framework that creates certain functional tests in order to simulate how a user may interact with an application. It is a library used on top of a web-based driver that writes the code in Ruby. This Ruby library has an advantage as it interacts with applications​ from a Rack level.

RSpec matchers

RSpec matchers are just RSpec-style aliases for methods that already exist in Capybara’s Node::Matchers class. They are basically built-in functions of the Matchers class used for the testing and debugging of data. The terminology makes use of the should keyword. Let’s look at a few examples:

have_content: The have_content matcher checks if the article has specific content, as typed in the brackets:

page.should have_content("Hello Word") 

have_selector: The have_selector matcher checks if the article of a specific title has specific tags, e.g., h2, h1, etc.

page.should have_selector("h1#article_title", text: article.title)

Similarly, the opposite of any matcher is done through the should_not keyword:

page.should_not have_content("Hello Word") 

For details on all the RSpec matchers, click here.

Code

Say you have a list and you want to check whether or not the list contains a specific element. If it does not contain that element, the test should fail, but if it does, the could will not fail. Let’s implement this:

  1. First, we need to define the matcher that we will use. In our case, the matcher is defined as contain.

  2. Define the array.

  3. Use the should keyword to find out if the element is part of the list or not.

Look at the code below, it’s written in Ruby:

Spec::Matcher.define :contain do |element|
match do |container|
container.include? element
end
end
describe Array do
it "Check element" do
arr=[1,2,3,"nine", "hello"]
arr.should contain "nine"
end
end

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved