Save 36% for Black Friday! Learn more

How to Test and Assert Link text is not on Page with Rails

Chris Oliver

December 10, 2019

Have you ever wanted to create an assert that tests if a link is NOT on the page with Rails? It's not easy to find an example of this. You can find some with Rspec, but not with Rails's builtin test suite using Minitest.

Typically you'll use assert_selector to find a match on the page like this:

assert_selector "a", "Edit Team"

This takes two arguments and searches for any anchor tags that contain the text "Edit Team" in them. If it finds it, the assertion passes.

Unfortunately there is no assert_not_selector or refute_selector method to execute the inverse of assert_selector. The assert_selector docs do mention someequality` options you can pass in, but the documentation is kind of hard to understand.

How do you test and assert a link is not on the page?

Well, you can pass in the text and count options and check for the count of 0. Easy as that.

assert_selector "a", text: "Edit Team", count: 0

To keep tests consistent, I like to use the same count selector when I want to check for presence too.

assert_selector "a", text: "Edit Team", count: 1

P.S. You might enjoy following me on Twitter.


Comments