RSpecでテストを書く時に、よく使うけど忘れがちな文法とかをまとめていこうと思います。
※随時書き足していきたい
- have_selector
have_selector 'h1', text: '大事なお知らせ' expect(page).to have_selector 'a[data-method=delete]', text: 'delete' expect(page).to have_selector 'h1', text: /^大事なお知らせ$/
- 複数ある要素の内、最初の要素を選択
all('.box-footer')[0].click_on '更新する' first('.box-footer').click_on '更新する'
- 最後に開いたタブへの切り替え
switch_to_window(windows.last)
- 画像を複数枚同時に保存できたことを検証する
複数枚画像を選択したいから、attach_fileで配列を使用。
%W
は配列を作るパーセント記法で、式展開がされる。
context 'トップ画像を複数枚アップロード' do it 'トップ画像が複数枚保存される' do attach_file('site_main_images', %W(#{Rails.root}/spec/fixtures/images/eye_catch.jpg #{Rails.root}/spec/fixtures/images/alexandros.jpeg)) click_on '保存' expect(page).to have_selector("img[src$='eye_catch.jpg']"), '複数画像が保存されていない' expect(page).to have_selector("img[src$='alexandros.jpeg']"), '複数画像が保存されていない' end end
- システムスペックで、ブラウザの挙動を確認
spec/rails_helper.rb
でpath/to/spec/support/**/*.rb
を読み込めるように設定
(spec/support/web_driver.rb) RSpec.configure do |config| config.before(:each, type: :system) do driven_by(:rack_test) driven_by(:selenium_chrome) # driven_by(:selenium_chrome_headless) end end
(spec/rails_helper.rb) Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }