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