I'm fairly new to programming, and I'm not sure what keywords I should be looking for.

I'm doing something like this right now:

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

I don't like it because it isn't scaling very well. I want to do something like:

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

It throws an undefined method error if I try to enter the type without quotes, but it's definitely not a string. How do I tell the script to use watir-webdriver span/button/image/etc?

有帮助吗?

解决方案

It's hard to figure out exactly what it is you want to do with this method or why it's even necessary--or why your type parameter would ever be anything other than a string--but here's a way to help you clean up your code that's similar to what orde suggested.

Note that it's unclear what you're implying when you say "it's definitely not a string." If it's not a string, what is it? Where is it coming from that you are sticking it into this method's parameters without knowing what type of Object it is?

So... I'm assuming your type doesn't have to be a String object, so I made it so it takes symbols...

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

其他提示

I'm not sure how you are calling your click method in your scripts, but here is a contrived example that seems to work:

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")

EDIT:

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top