DEV Community

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

Posted on • Updated on

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.

Top comments (0)