LoginSignup
2
0

More than 3 years have passed since last update.

ドライバがSeleniumのテストでPOSTしたくなったらドライバをRack::Testに変える

Last updated at Posted at 2020-12-29

結論

Capybara.current_driver=というメソッドを使うとテストの途中でもWebDriverを切り替えられる

問題

CapybaraのドライバにSeleniumを用いたWebDriverを指定してfeature specを実行すると、WebDriverを通じて実際にブラウザを動かしてテストできる。

OAuth認可サーバをテストでのアクセストークンの取得のように、ブラウザで操作したあと、さらにAPIコールすることで完結するシナリオをひとまとまりのexampleにしたいことがある。しかし、実際のブラウザと同じで、いきなりPOSTやPUTをリクエストとして発行できない。

解決策

exampleの途中でCapybara.current_driver=を使ってWebDriverを:rack_test (Rack::Test)に切り替えると、Rack::Testは各種HTTPリクエストを発行できるメソッドを持つので、exampleの中でPOSTやPUTを発行できる。

spec/rails_helper.rb
Capybara.default_driver = :selenium
spec/features/authorization_spec.rb
# `js: true`を指定したテストなので最初はドライバが`:selenium`になっている
# cf. https://github.com/teamcapybara/capybara#using-capybara-with-rspec
scenario '利用者が認可してクライアントがアクセストークンを取得する', js: true do
  # ブラウザ操作を書く
  visit oauth_authorization_path
  fill_in id: 'id', with: id
  fill_in id: 'password', with: password
  click_button 'ログイン'

  # ...

  # ここでは`page.driver.post`はNoMethodErrorを投げる

  # ドライバをRack::Testに変える
  Capybara.current_driver = :rack_test

  # pageから引けるRack::Testドライバのオブジェクトが
  # 各種HTTPメソッドを持つのでPOSTを発行できる
  page.driver.post oauth_token_path # ...

  # ...
end
2
0
0

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
2
0