Search code examples
rubywatir

Watir: Passing dynamic selector


Is there a way to pass a dynamic set of options to a textarea element in browser?

options = {
    :type     => 'textarea',
    :selector => ':id',
    :field    => 'id_of_textarea_field',
    :value    => 'Joe Salesperson'
}    

browser.textarea(options[:selector] => options[:field]).set ''

Error received:

invalid attribute: ":id"

A similar thread is listed here (selecting elements using variables in ruby /watir) but no answer.


Solution

  • options = {
        :type     => 'textarea',
        :selector => :id,
        :field    => 'id_of_textarea_field',
        :value    => 'Joe Salesperson'
    }
    

    You can just pass the identifier, no need for quotes.


    2017-01-03, Updating with a use case. Here is the declaration of the method I'm using and the call. The actual code is much more verbose and contains different validations than what I've pasted here. In the example, you'll notice a simple switch block which sets the appropriate information based on the element type passed (specifically text areas, text fields, and select elements).

    def validateInput(options = {})
        success   = true
    
        begin
            case options[:type]
                when 'textarea', 'text_field'
                    Watir::Wait.until{$browser.textarea(options[:selector] => options[:field]).present?}
    
                    $browser.textarea(options[:selector] => options[:field]).set options[:value]
                when 'select'
                    $browser.select_list(options[:selector] => options[:field]).select_value options[:value]
                else
                    puts "in else"
                end
            end
        rescue => e
            $message.push("Failed to validate '#{options[:field]}' field. #{e}")
            success = false
        end
    
        return success
    end
    
    
    validateInput({
        :type     => 'textarea',
        :selector => :id,
        :field    => 'order_approval_comment_name',
        :value    => 'Joe Salesperson'
    })