参考)
https://www.rubydoc.info/github/jnicklas/capybara/Capybara
https://github.com/teamcapybara/capybara
https://qiita.com/morrr/items/0e24251c049180218db4
railsへのインストール
Gemfilesへ追記し、bundle installでインストールする。
rails 5.2.2では初期インストールされていた。
使い方
参考)
https://github.com/teamcapybara/capybara#using-capybara-with-rspec
テストスクリプトの配置
spec/features/以下
または
spec/systems/以下にxxxxx_spec.rbとして配置する。
※機能中心にテストするならfeatures以下、表示中心にテストするならviews以下に配置するのかと想像している。systems/以下はどのようなケースで使うべき?
記述内容サンプル
/hello/indexページにhelloと表示されているかを確認する場合
require 'rails_helper' describe "capybaraの実験", type: :feature do before :each do # 何か事前に必要な処理などがあれば visit '/hello/index' # 指定urlへアクセス end # RSpecマッチャー(以下参照)を使うサンプル # pageはページ自体を表す it "アクセスできるかテストする" do expect(page).to have_content "hello" end # 要素を取得して、その属性が意図しているものか確認するサンプル it "全ての画像タグが挿入されているか" do all('.imageList__img').zip(get_all_urls) do |element, expected_url| expect(element[:src]).to eq(expected_url) end end # 要素を指定して取得して、そのinnerHTMLの要素が意図しているものか確認するサンプル it "表示されている名前がただしいか?" do elm = find('#name') expect(elm.text).to eq("山田太郎") end
RSpecで使う場合のマッチャー
一覧)
https://www.rubydoc.info/github/jnicklas/capybara/Capybara/RSpecMatchers
上記サンプルのhave_contentは指定した文字列を含んでいるかどうかをチェックしてる。
capybaraのElementクラスのメソッド一覧
一覧)
https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Element
要素に対して、クリックを行ったり、テキストを挿入したりするメソッドもある。
element[:src]
のような書き方でその属性にアクセスできる。
実行方法
RSpecを実行したら実行された。
bundle exec rspec