Search code examples
cucumbercapybara

What are the differences between the find() and expect() selectors?


I am studying automated tests with capybara and cucumber, and my tests ended up getting a little messy because I use two methods to search for text on the page.

My question is, which one has the best application for the tests, and why use this specific selector?

So my page is structured like this

HTML

<p>some cool text</p>

Seletores

#find selector
page.find('p', text: 'some cool text')

#expect selector
expect(page).to have_text('some cool text')

Solution

  • find and have_text are the Capybara provided methods in your example. find is a method which returns the matching element for you to further interact with (use for scoping, etc), whereas have_text (and a bunch of others) is an RSpec matcher used with RSpecs expect method to specify something you expect to see or not see on the page. If you need the element for further actions use find, if all you're doing is checking whether or not something on the page exists use expect

    fyi - the equivalent expectation to your find would be

    expect(page).to have_css('p', text: 'some cool text')