當我將一段代碼移動到另一個文件時,我無法使用該方法。無法訪問超出相同文件的方法變量
下面提到的代碼工作導致所有代碼都在一個文件中。
require 'rubygems'
require 'watir'
require 'win32ole'
require 'erb'
require 'ostruct'
require 'C:/classes/html.class'
require 'C:/classes/Xls'
require 'C:/classes/screen_capture'
require 'C:/classes/RequiredRubies'
include Watir
begin
xlFile = XLS.new(Dir.pwd + '/testdata.xls')
myData = xlFile.getRowRecords('a2:z3','Pit')
xlFile.close
myData.each do |record|
@ie = IE.new
@ie.maximize
@ie.goto (record['Url'])
@ie.focus
end
end
上面的代碼'URL'出現在Excel表名testdata.xls中。上面的代碼工作得很好。可以說這個文件的名稱是file1.rb
但我想將瀏覽器的打開到不同的文件,以便我不在所有的測試文件中使用此代碼,並只在一個文件中使用它,並從它調用到所有其他測試。以下是我所做的改變,但這不起作用。
在File1.rb我一直在那裏我剛纔提到的通用代碼來打開瀏覽器
require 'C:/function.rb
include Watir
include Commonfunctions
begin
xlFile = XLS.new(Dir.pwd + '/testdata.xls')
myData = xlFile.getRowRecords('a2:z3','Pit')
xlFile.close
myData.each do |record|
openie = openbrowser
end
end
所需的全部文件+新的文件,我已經創建了一個文件打開瀏覽器,我想用作普通功能。讓我們在function.rb說
所需的全部文件+下面的代碼文件名
include Watir
module Commonfunctions
def openbrowser
@ie = IE.new
@ie.maximize
@ie.goto (record['Url'])
@ie.focus
end
end
現在,當我跑我的file1.rb我得到下面的錯誤
C:/function.rb:17:in `openbrowser': undefined local variable or method `reco
rd' for main:Object (NameError)
from test.rb:23:in `block in <main>'
from test.rb:21:in `each'
from test.rb:21:in `<main>'
「錄音」對象來自不同的文件,這是我的數據驅動器。在該文件中,這是方法記錄存在的代碼
numRecords = myRange.Rows.Count
(0..numRecords-1).each do |i|
record=[]
areas.each do |area|
record.concat(area[i])
end
#Clean up formatting
record.collect! do |x|
if x.is_a?(Float) and x % 1 == 0
x.to_i.to_s
else
x.to_s.strip
end
end
data << record
end
return data
end
任何人都可以幫助我解決此問題。我想將所有常用函數移動到一個文件中,並在所有測試中使用這些函數,而不是在所有測試中編寫相同的函數。
感謝您的回覆。我嘗試了你所提到的並按照預期工作。我還有一個問題。如果在我的函數openbrowser記錄中有兩個參數,比如@ ie.goto(record ['Url'])和(:name,「Q」).set(record ['test]),會發生什麼?然後如何處理.. – anagraj 2012-03-26 14:13:22
@anagraj只是將更多的參數添加到'def openbrowser'並在它使用的代碼和方法中適當地使用它們。 – dbenhur 2012-03-27 04:47:42