LoginSignup
13
13

More than 5 years have passed since last update.

CapybaraでのJSのconfirmダイアログのテストについて

Last updated at Posted at 2015-06-11

大いにはまったので・・・。

主にdeleteの時のcomfirmはどうするかと、ネストについて

gemのインストール、設定はできてるものとして・・・。

すいません、ご指摘いただいたので記載します。何か不足な点があるかもしれないですが(汗 遠慮なくご指摘いただけると幸いです。

Gemfile

gem 'capybara'
gem 'capybara-webkit'

rails_helper.rb内に以下を追記

Capybara.javascript_driver = :webkit

動作:

  • showに'Delete'リンクだけがある
  • 無事削除できたらルートへリダイレクト、"Successfully Deleted a Pin"のメッセージを出す
require 'rails_helper'

RSpec.feature "Deleting Hoges", type: :feature, js: true do
  let(:hoge) { FactoryGirl.create(:hoge) }

  background do
    visit hoge_path(hoge)

    expect(page).to have_link 'Delete', href: hoge_path(hoge)

    link = find_link 'Delete'
    expect(link['data-confirm']).to eq 'Are you sure?'
  end


  scenario "Accepting a confirm" do
    page.accept_confirm 'Are you sure?' do
      click_link 'Delete'
    end
    expect(current_path).to eq root_path
    within '.alert' do
      expect(page).to have_content "Successfully Deleted a hoge"
    end
  end

  scenario "Dissmissing a confirm" do
    page.dismiss_confirm 'Are you sure?' do
      click_link 'Delete'
    end
    expect(current_path).to eq hoge_path(hoge)
  end
end

featureの行に, js: trueを追加するのを忘れずに。

まず、background内でページにvisitしておく。beforeみたいなもの?

ついでに'Delete'リンクのdata-confirmの値を確認。

page.accept_confirmを使う。それにブロックを渡す。

ブロック内にはそのconfirmを発火させる動作。この場合は'Delete'というリンクをクリックする。

background内で一応メッセージの内容は確認しているが、実際に表示されるかどうか、ってところでpage.accept_confirm 'Are you sure?'とする。メッセージは指定しなくてもいいかもだけど。

accept_js_confirmというのがdeprecatedになってた。新しい情報が少なかった・・・。

で、OKを押した場合とキャンセルした場合の2つに分岐したい。

ネストはここでマージされた模様。

あとはcurrent_pathとか便利。リダイレクトかレンダリングした後の画面のパス確認

13
13
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
13
13