Testing non-existence

Given a test like this one:

1expect(page).to have_css("[data-search-results]")
2click_on "Hide results"
3expect(page).not_to have_css("[data-search-resutls]") # Typo!

Something like this may pass in your codeā€¦ but it is not testing what you think it is testing. There is a typo in the second expectation, so of course it is not going to find [data-search-resutls], regardless of whether your app is working as intended or not.

To avoid this situation, I always put the thing to look for (in this case the CSS selector) in a variable, and then I use this variable for both the test of existence and the test of non-existence:

1results_selector = "[data-search-results]"
2expect(page).to have_css(results_selector)
3click_on "Hide results"
4expect(page).not_to have_css(results_selector)

This way, a typo will make the first expectation fail, and the issue will be made evident.

It is important that there is also a test of existence (first expectation in this example). It does not matter if this is as an assertion/expectation in the same test, or in a separate one. Having only a test that checks for non-existence of something can be misleading for the same reason: your target may not be present for completely different reasons from what you expect.