DEV Community

Cover image for Avoiding stale elements in Capybara tests
Jan Schröder
Jan Schröder

Posted on • Edited on

4 1

Avoiding stale elements in Capybara tests

Yesterday night, I encountered a new error: StaleElementReferenceError.

What it is? It is an error thrown by Selenium WebDriver, in my case used in a Capybara test with Ruby.

It is thrown, when the reference to the selected element changed.

In my case, I was testing an uploading function and was checking to see the preview image once the upload had finished.

The mistake in writing the test that I made, was that I was declaring a variable, where I was storing the selected element.

Then('(I )see the preview of {string}') do |name|
  preview_image = page.find(".preview-image")
  expect(preview_image[:style]).to include(name)
end
Enter fullscreen mode Exit fullscreen mode

After the image appeared, React changed the DOM and put a new element with the image. This caused the reference inside the variable to get, well, stale. And so, on one of the retries, Capybara threw the error.

This situation can easily be avoided, by writing the test without the variable like so:

Then('(I )see the preview of {string}') do |name|
  expect(page.find(".preview-image")[:style]).to include(name)
end
Enter fullscreen mode Exit fullscreen mode

This way, Capybara checks for the element on every retry.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay