4

How can I wait for an image to load using Capybara? Here's my app code:

-- <img src="data:image/jpeg.*" class="some class" alt="Image">

I have tried using the wait_for method using those class and img attributes with no luck. It never waited for that image to load.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
SaeeK
  • 217
  • 1
  • 4
  • 12
  • Welcome to Stack Overflow. If you tried using `wait_for` show us the minimal code demonstrating that. Read "[ask]" and "[mcve]". – the Tin Man Dec 22 '15 at 22:10

1 Answers1

2

img elements have a complete property that indicates whether the image is loaded or not. Therefore something along the lines of

start = Time.now
while true
  break if find('img.some_class')['complete']
  if Time.now > start + 5.seconds
    fail "Image still not loaded"
  end
  sleep 0.1
end

would wait up to 5 seconds for the image to finish loading, assuming the img element is already on the page.

This could also be implemented as a custom selector with something along the lines of

Capybara.add_selector(:loaded_image) do
  css { |locator_class| "img.#{locator_class}" }
  filter(:loaded, default: true, boolean: true) { |node, value| not(value ^ node['complete']) }
end

which could then be called as

find(:loaded_image, 'some_class')

*** Note: I haven't actually tried the custom selector code, but it should be close enough to provide guidance

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78