1
votes

I am having trouble using a variable in browser reference. I am trying to pass the field type such as ul, ol etc. The code works if I type ol, but I would like to use the pass variable labeled 'field'. I recieve an "undefined method for field" error.

I have tried also using #{field}, but that does not work either. The error is that field is not defined.

def CheckNewPageNoUl(browser, field, text1, output)

  browser.a(:id => 'submitbtn').hover
  browser.a(:id => 'submitbtn').click
  output.puts("text1  #{text1}")      
  browser.body(:id => 'page').wait_until_present
  if browser.table.field.exists?
    output.puts(" #{text1} was found in CheckNewPageNoUl")
  end
end

field = "ol" 

text1 = "<ol>"

CheckText.CheckNewPageNoUl(b, field, text1, outputt)
1
In the code example, the field variable is a String. The browser object is expecting a method where the class is Watir::OList (or Watir::Ol in watir-classic). - orde
I understand that field is a string but why doesn't it get translated to 'ol' in the line of code so that it gets interpreted as "browser.table.ol.exists?" I was hoping to use the method for ul, ol, li, etc by passing a variable and not making several more methods. Thanks for the help. - coolercargo

1 Answers

3
votes

To translate a string into a method call, use Object#send, which can take two parameters:

  1. The method name (as string or symbol)
  2. Arguments for the method (optional)

Some examples:

field = 'ol'
browser.send(field).exists?
#=> Translates to browser.ol.exists?

specifiers = {:text => 'text', :class => 'class'}
browser.send(field, specifiers).exists?
#=> Translates to browser.ol(:text => 'text', :class => 'class').exists?

For your code, you would want to have:

if browser.table.send(field).exists?
  output.puts(" #{text1} was found in CheckNewPageNoUl")
end