So I got the chance to use Watir again on a short project at work. The last time I used it was about 1.5 years ago, and I was glad to find out that Watir is still a nice library to use. Watir simply works without much hassle.
The only issue I had was with image saving. From Image class documentation (Watir 1.6), it wasn’t obvious that save can only be called when image element is directly contained within a browser element.
I was trying to save the first image within a div,
$browser.div(:id, 'foobar').images[1].save('d:\temp')
NoMethodError: undefined method `goto' for #<Watir::Div:0x3fa5d7c>
d:/dev/ruby/lib/ruby/gems/1.8/gems/watir-1.6.2/lib/watir/image.rb:113:in `save'
Looking at the implementation of save in image.rb,
def save(path)
require 'watir/windowhelper'
WindowHelper.check_autoit_installed
@container.goto(src)
begin
thrd = fill_save_image_dialog(path)
@container.document.execCommand("SaveAs")
thrd.join(5)
ensure
@container.back
end
end
I ended up having to use XPath because the image element doesn’t have any id or class that allows me to directly reference it from a browser element.
$browser.image(:xpath, "//div[@id='foobar']/img").save("d:\temp")
Another nice improvement to the save method implementation would be instead of going to the image src and then clicking back, which could potentially lose the state of a page, it would be nicer to open a new window and close it afterward.