我在寫一個watir腳本來測試上傳表單。如何用watir和IE上傳文件?
但該腳本不會自動選擇要從我的硬盤上傳的文件。
IE會在文件選擇器對話框打開的情況下停止。只要我在對話框中手動選擇要上傳的文件並單擊確定,watir會根據需要繼續。我想知道它爲什麼會停止。
這是我的Watir腳本:
require 'test/unit'
require 'watir'
# runs on win3k, IE 6.0.3790; ruby 1.8.6, watir
class EpcHomePage < Test::Unit::TestCase
def test_upload
ie = @browser
htmlfile = "C:\\testing\\upload.html"
uploadfile = "C:\\testing\\upload.html"
ie.goto(htmlfile)
ie.file_field(:name,"file1").set(uploadfile)
assert_equal uploadfile, ie.file_field(:name,"file1").value
ie.button(:name, 'upload').click
end
def setup
@browser = Watir::IE.new
end
def teardown
@browser.close
end
end
我的代碼從這個頁面:http://wiki.openqa.org/display/WTR/File+Uploads
這是形式:
<html><body>
<form name="form1" enctype="multipart/form-data" method="post" action="upload.html">
<input type="file" name="file1">
<input type="submit" name="upload" value="ok">
</form>
</body></html>
我發現這個手動http://svn.openqa.org/svn/watir/trunk/watir/unittests/filefield_test.rb也。我正在使用IE 6和IE 7進行測試。
編輯:我已上載我在這裏簡單的例子(3檔住在C:\我的機器測試\,只需啓動CMD文件):
http://dl.dropbox.com/u/1508092/testing.rar
它未能在3不同的機器(所有Windows 2003,2x IE 6和1 x IE 7)。我也改變了腳本c:\ ruby \ lib \ ruby \ gems \ 1.8 \ gems \ watir-1.6.5 \ lib \ watir \ input_elements.rb中的睡眠時間從1秒到5秒,就像ŽeljkoFilipin在他的回答:
def set(path_to_file)
assert_exists
require 'watir/windowhelper'
WindowHelper.check_autoit_installed
begin
Thread.new do
sleep 5 # it takes some time for popup to appear
system %{ruby -e '
...
這是它停止(請注意,我沒有手動導航到該文件對話框一旦在該目錄從IE瀏覽器這一點始終會顯示此目錄中打開的對話框,但也不。 ,並不意味着腳本選擇的目錄,我認爲這意味着IE瀏覽器總是顯示上次目錄在那裏左):
this is where it stops http://dl.dropbox.com/u/1508092/upload-dialog.JPG
編輯:
我發現,在OLE32代碼查找英文名稱:
POPUP_TITLES = [ '選擇文件', '選擇要上傳的文件']
我安裝了IE 7的英語版本現在。仍然沒有成功。但我認爲它與本地化有關,因爲input_elements.rb搜索窗口標題。我想知道爲什麼它現在仍然失敗。這是input_elements.rb代碼:
class FileField < InputElement
INPUT_TYPES = ["file"]
POPUP_TITLES = ['Choose file', 'Choose File to Upload']
# set the file location in the Choose file dialog in a new process
# will raise a Watir Exception if AutoIt is not correctly installed
def set(path_to_file)
assert_exists
require 'watir/windowhelper'
WindowHelper.check_autoit_installed
begin
Thread.new do
sleep 2 # it takes some time for popup to appear
system %{ruby -e '
require "win32ole"
@autoit = WIN32OLE.new("AutoItX3.Control")
time = Time.now
while (Time.now - time) < 15 # the loop will wait up to 15 seconds for popup to appear
#{POPUP_TITLES.inspect}.each do |popup_title|
next unless @autoit.WinWait(popup_title, "", 1) == 1
@autoit.ControlSetText(popup_title, "", "Edit1", #{path_to_file.inspect})
@autoit.ControlSend(popup_title, "", "Button2", "{ENTER}")
exit
end # each
end # while
'}
end.join(1)
rescue
raise Watir::Exception::WatirException, "Problem accessing Choose file dialog"
end
click
end
end
文本「選擇文件」現在出現在我的新的IE的標題。還有什麼應該在這裏進行本地化或更改?我將屏幕截圖更新爲英文版。
我在Internet Explorer中使用Watir的文件上傳很多,我也注意到它有時不會選擇文件,但它幾乎爲我所有的時間。它根本不適合你? – 2010-04-22 08:55:29