簡體   English   中英

你能通過變量選擇watir命令嗎?

[英]Can you choose watir commands through a variable?

我對編程很新,而且我不確定我應該尋找什么樣的關鍵字。

我現在正在做這樣的事情:

def click(text, type)
  b.span(:text=> text).click if type == 'span'
  b.button(:name=> text).click if type == 'button'
  b.image(:src=>text).click if type == 'image'
  b.button(:title=>text).click if type == 'title'
end

我不喜歡它,因為它不能很好地擴展。 我想做的事情如下:

def click(text,type)
  b.type(:text=> text).click
end

如果我嘗試輸入沒有引號的類型,它會拋出一個未定義的方法錯誤,但它肯定不是一個字符串。 如何告訴腳本使用watir-webdriver span / button / image / etc?

我不確定你是如何在你的腳本中調用你的click方法的,但這是一個似乎有用的例子:

require 'watir-webdriver'

def click_method(element, text)
  @b.element(:text => "#{text}").click  
end

@b = Watir::Browser.new
@b.goto "http://www.iana.org/domains/reserved"

click_method("link", "Domains")

編輯:

require 'watir-webdriver'

def method_not_named_click(el, locator, locator_val)
  if locator_val.is_a? String
    @b.send(el, locator => "#{locator_val}").click
  elsif locator_val.is_a? Integer
    @b.send(el, locator => locator_val).click
  end
end

@b = Watir::Browser.new
@b.goto "http://www.iana.org/domains/reserved"

method_not_named_click(:a, :text, "Domains")
method_not_named_click(:a, :index, 3)

很難弄清楚你想要用這種方法做什么,或者為什么它甚至是必要的 - 或者為什么你的類型參數不是字符串 - 但這里是一種幫助你清理代碼的方法類似於orde建議的。

請注意,當你說“它絕對不是一個字符串”時,你不清楚你所暗示的是什么。 如果它不是字符串,它是什么? 它是從哪里來的,你將它堅持到這個方法的參數而不知道它是什么類型的對象?

所以...我假設你的類型並不一定是一個String對象,所以我做了它,所以它需要的符號......

def click(text, type)
  types={span: :text, button: :name, image: :src, title: :title }
  @b.send(type, {types[type]=>text}).click
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM