how to select dropdown having Encoding::UndefinedConversionError in watir?

519 Views Asked by At

I want to select dropdown having text="Côte d'Ivoire".

ie.select_list(:id, "name01").select("#{text}")

I tried these codes,

1.encoding: UTF-8 #not working

2.text.force_encoding("ASCII-8BIT").encode('UTF-8', undef: :replace, replace:'') #text=Cte d'Ivoire

what should I do for it? I also want to save this text to my DB.Please help.

2

There are 2 best solutions below

3
On

If you know the string is UTF-8 encoded, why not just force encoding to UTF-8?

#encoding: ASCII-8BIT
str = "C\xC3\xB4te d'Ivoire" # => "C\xC3\xB4te d'Ivoire"
str.encoding # => #<Encoding:ASCII-8BIT>

str.force_encoding('UTF-8')
str # => "Côte d'Ivoire"
str.encoding # => #<Encoding:UTF-8>

If you are using Côte d'Ivoire as a literal anywhere in your Ruby source files, be sure to add

#encoding: UTF-8

as the first line of the file to tell Ruby that the file is UTF-8 encoded.

4
On

I would have expected your solutions to work, unless the software you are using to save/execute the files is overriding the setting. I recall having that issue with NetBeans.

An alternative, if you cannot fix the actual encoding, is to use a regex to match just the standard characters.

text = /C.te d'Ivoire/
browser.select_list.select(text)

The regex has replaced all accented characters with a ..

Not a great solution, but perhaps a solution if nothing else works.