Skip to content

Instantly share code, notes, and snippets.

@bluerabbit
Last active April 22, 2022 01:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluerabbit/6227860 to your computer and use it in GitHub Desktop.
Save bluerabbit/6227860 to your computer and use it in GitHub Desktop.
capybaraのAPIメモ

操作

  • ページに移動
visit '/pages/new'
  • フォームに値を入力
fill_in 'id_or_label_text', with: 'yamada'
  • ラジオボタンを選択
choose 'ラジオボタン1'
  • チェックボックスをチェック/非チェック
check('チェックボックス1')
uncheck('チェックボックス1')
  • ファイルの添付
attach_file 'file', "#{fixture_path}/xxx.csv"

最近はinput type=fileを隠してボタンを上に出してたりすることが多いので、その場合はvisible: falseが必要

attach_file 'file', "#{fixture_path}/xxx.csv", visible: false
  • セレクトボックスで選択
select('カテゴリ1', from: 'カテゴリ')
  • ボタンまたはリンクをクリック
click_on 'ボタンまたはリンク'

検証

  • 現在のページを確認
current_path.should == '/pages/1'
  • Http Statusを確認
page.status_code.should be(200)
  • タイトルタグの検証
page.should have_title('たいとる')
  • ページ内に期待する文字列が(ある|ない)か確認
should have_content '登録されました'
should have_no_content 'エラーがしました'
  • チェックボックス(radio)がチェックされて(いる|いない)
have_checked_field
have_unchecked_field
  • selectの値を検証する
page.should have_select('name', selected: 'selected_value')
  • inputの値を検証する
should have_field('id_or_label', with: 'value')
  • テーブルの行数を検証する
all('#table_id tr').should have(0).rows
page.should have_css("table#table_id tbody tr", count: 0)
  • 表示・非表示の検証をする
find('#css_selecter').should be_visible
  • disabledかを検証する
expect(page).to have_checked_field '選択肢1', disabled: true
expect(page).to have_button '登録', disabled: true 
  • テーブルが存在するか
should have_table('table')
  • セレクターを使った検証
should have_selector('button', value: '実行')
should have_selector('h1#title', :content=>'Hello!')
should have_css('#status.current')
  • ボタンが存在するか
find('#navigation').should have_button('Sign out')
  • ある要素が表示されているか
should have_selector('#hoge_area', visible: true)

debug

  • 現在のページをブラウザで表示
save_and_open_page
  • debuggerを起動
binding.pry

使ってはイケナイ(?!)

  • xpath引数を使ったfind
find(:xpath, '//li[contains(.//a[@href = "#"]/text(), "foo")]').value
  • xpath引数を使ったfind
    • containsを使う事でclassに複数指定があってもヒットする
all(:xpath, "//a[contains(@class, 'target-class-name') and contains(text(), 'リンク名')]")
  • findした要素の値をshouldではなく参照する
find('#id').text
  • ボタンクリックする時にclick_on以外を使う
find('#id').click
click_button 'id_or_label'

Link

@bluerabbit
Copy link
Author

page.find('#hoge') # 存在しないとエラー
page.first('#hoge') # 存在しないとnil
page.all('table')     # 存在するelement全てを取得

@bluerabbit
Copy link
Author

within(".your_selector") do
  
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment