Capybaraでテスト中のHTMLをダンプしてデバッグする

カピバラさんでテストが通らないんですけど、テスト中のナマのHTML見たいんだけどどうなってんのという時の技。

準備としてpry-byebugというgemを使うのでGemfileに書いてbundle installとかして下さい。

gem 'pry-byebug'

あとはデバッグで止めたい場所にこんなかんじで、binding.pryをitで囲んだブロックを挟む。itで囲むのがポイント。itの外だと変数セットされないっぽい。

describe "Search Page" do
    describe "Search" do
      before {
        31.times { FactoryGirl.create(:commit) }
        visit commits_search_path
        fill_in "keyword", with:"Message"
        click_button "Search"
      }
      after { Commit.delete_all }

      it 'test' do
        binding.pry
      end

      it { should have_content('31 results.') }
      it { should have_selector('table') }
      it { should have_content('Message') }
      it { should have_selector('div.pagination') }

      describe "Pagination" do
        before { all('.pagination')[1].click_link('2') }
        it { should have_content('Message') }
      end
    end
  end

この状態でテスト走らせるとbinding.pryの行で止まってpryのREPLが立ち上がるので、

pry> page.html

とすればCapybaraでテスト中のHTMLのダンプが見れる。

参考