LoginSignup
9
8

More than 5 years have passed since last update.

Selenium2+Ruby で作業自動化

Last updated at Posted at 2015-03-14

Ruby の準備

これでやってた。
http://qiita.com/8mamo10/items/677d62fa0348f5bb4824

Selenium のインストール

gem install selenium-webdriver

簡単なサンプルで動作確認

これで firefox 立ち上がって、google 開いて、firefox 終了したらきっと OK。

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.navigate.to 'https://www.google.co.jp/'
driver.quit

この辺に、もうちょっと詳しく載ってる。
https://code.google.com/p/selenium/wiki/RubyBindings

ブラウザでの登録処理を自動化した例

テストで、まとまった数のユーザを登録する必要があったので。
これを実行すると、firefox で 30 人ユーザ登録してくれる。

登録処理の遷移は、入力ページ確認ページ登録完了ページ

(2015/7/30) riocampos さんからの指摘を受けてコード微修正

require 'selenium-webdriver'

# 各入力欄で、何入れるか・何選択するかの対応表
# メールアドレスとかは少しずつ値をずらしてる
text = [
  ['last_name',     'test_%d'],
  ['first_name',    'test_%d'],
  ['nick_name',     'test_%d'],
  ['user_mail',     'test_%d@example.com'],
  ['user_password', 'test'],
  ['user_password_confirm', 'test'],
]

select = [
  ['user_pref',         1],
  ['user_birth[year]',  30],
  ['user_birth[month]', 1],
  ['user_birth[day]',   1],
]

radio = [
  ['user_sex',   0],
]

driver = Selenium::WebDriver.for :firefox

# メールアドレスが重複すると登録失敗するんで、
# 前回どこまで数字使ったかを覚えておいて、start の値を決める
start = 0
# 何回登録処理を行うか
num = 30

num.times do |i|

  # 入力ページの URL
  driver.navigate.to 'http://xxxxxx'

  text.each do |id, data|
    element = driver.find_element(:id, id)
    s = sprintf(data, start + i);
    element.send_keys(s);
  end

  select.each do |id, data|
    element = Selenium::WebDriver::Support::Select.new(driver.find_element(:name => id));
    element.select_by(:index, data)
  end

  radio.each do |id, data|
    elements = driver.find_elements(:name, id)
    elements[data].click
  end

  # 入力ページの submit をする
  driver.find_element(:xpath, '/html/body/div[3]/div[2]/div/div/form/div/input').click
  # 確認ページの submit をする
  driver.find_element(:xpath, '/html/body/div[3]/div[2]/div/div/form/div/input[2]').click

  # 登録完了ページが表示される
end
9
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8