Quick Tip: Verify a HyperLink Exists Without Clicking it
How to verify a link without clicking it.
Here is a small test automation task: Verify that the client “Toby Williams” has been soft deleted (i.e. the user has been deleted but it can still be restored).
As humans, we can tell that the client name has a strikethrough (visually) and there is a new blue “Restore” link next to their name.
As part of an automated test, verifying the strikethrough effect (via CSS) might not be the best option. Instead, let’s take a look at how we could verify a soft delete via the Restore link.
Clicking the “Restore” link is not appropriate — we don’t want our test to actually restore the client.
driver.find_element(:id, "restore_client_link").click # no good
Clicking the button might also redirect to another page, breaking the testing flow (we may need to continue the testing process on the same page).
And I don’t want to verify the text ‘Restore’ in the HTML source, which is too generic. The word ‘Restore’ might exist in a paragraph of text.
expect(page_source).to include("Restore") # no good
So, how can we verify a hyperlink without clicking it? Easy, just drop the `.click`.
driver.find_element(:id, "restore_client_link")
If the link is not found, Selenium WebDriver will return an ElementNotFound error, causing the test to fail anyway.
Using the element ID like above works. A more readable alternative is to assert with the link text.
driver.find_element(:link_text, "RESTORE")
Note: For keen readers that might have picked up on it:
driver.find_element(:link_text, "Restore")
— which matches what is on the HTML source above, will not work. Since a few years ago, Selenium/ChromeDriver changed link text locating to what is visible to the user (RESTORE), as opposed to what is in the plain HTML (Restore).