こんにちは、Watir を使用して自動化テスト スクリプトを作成しています。テキスト フィールド内の既存の文字列に文字列を追加しようとしました。次のコード行を使用して、テキスト フィールドの末尾に追加する方法を理解できました。
browser.text_field(:id => "custom-preview-text").append "Hello World"
この行を変更して、テキスト フィールド内の特定の文字列の後にこのテキストを追加するにはどうすればよいですか?
こんにちは、Watir を使用して自動化テスト スクリプトを作成しています。テキスト フィールド内の既存の文字列に文字列を追加しようとしました。次のコード行を使用して、テキスト フィールドの末尾に追加する方法を理解できました。
browser.text_field(:id => "custom-preview-text").append "Hello World"
この行を変更して、テキスト フィールド内の特定の文字列の後にこのテキストを追加するにはどうすればよいですか?
これを実現する 1 つの方法を次に示します。
require 'watir-webdriver'
b = Watir::Browser.new
b.goto 'https://www.google.co.in/search?output=search&sclient=psy-ab&q=gdg&btnK='
elem = b.text_field(:id => "gbqfq")
val = elem.value
elem.clear
elem.send_keys val + "Good bye!"
puts elem.value
# >> gdgGood bye!
特定の文字列の後にテキストを挿入したい場合は、テキスト フィールドの文字列を取得し、Ruby を使用して新しい文字列を決定し、新しい文字列をテキスト フィールドに入力する必要があると思います。
を使用gsub
して、文字列の特定の部分の前後にテキストを挿入できます。例えば:
original_text = 'word1 word2 word3'
# Insert text before word2
p original_text.sub(/(?=word2)/, 'insertion ')
#=> "word1 insertion word2 word3"
# Insert text after word2
p original_text.sub(/(?<=word2)/, ' insertion')
#=> "word1 word2 insertion word3"
テキスト フィールド内に新しい文字列を挿入すると、次のようになります。
# Get the current text field value
text_field = browser.text_field
original_text = text_field.text
# If you want to insert before word 2
new_text = original_text.sub(/(?=word2)/, 'insertion ')
# If you want to insert after word 2
new_text = original_text.sub(/(?<=word2)/, ' insertion')
# Set the text field with the new value
text_field.set(new_text)
この解決策は、既存のテキストを再入力してもかまわないことを前提としていることに注意してください (つまり、テストを起動して台無しにする JavaScript はありません)。