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

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
Loading...

Want to stay up-to-date with Ruby on Rails?

Join 35,909+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.