RoRでデバッグ
はじめに
システム情報
- Ruby 2.6.5
- Rails 5.2.3
- bundler 1.17.2
- puma
- rbenv local環境下
デバッグ用のライブラリ群
pry-rails(rubygems)
Rails console で Pry が起動するようになる
pry-rails を入れるまでは irb が起動する
show-routes などのコマンドが Rails console で使えるようになる
Rails console で help と打つと、使えるコマンドがわかる
binding.pry をソースコード中に挟むとそこがブレークポイントとなり、そこで処理を止めてデバッグできるようになる
pry-rails だけではステップ実行はできない
pryの使い方
Rails-console
> help
**Navigating pry**
!pry Start a pry session on current self.
disable-pry Stops all future calls to pry and exits the current session.
exit Pop the previous binding.
exit-all End the current pry session. ブレークポイントで停止した状態から解放する(デバッグの終了)
exit-program End the current program.
jump-to Jump to a binding further up the stack.
nesting Show nesting information.
switch-to Start a new subsession on a binding in the current stack.
pry-byebug(rubygems)
binding.pry で止めたところからステップ実行ができる
例えば next コマンドで一行ずつ実行できる
こちらも詳細は Rails console の help などを参照
byebugの使い方
Rails-console
> help
**Byebug**
backtrace Display the current stack.
break Set or edit a breakpoint.
continue Continue program execution and end the pry session.ブレークポイントで停止した状態から解放する(デバッグの終了)
down Move current frame down.
finish Execute until current stack frame returns. 現在のスタックを終了する(ステップアウト:レシーバ呼び出し部分に戻る)
frame Move to specified frame #.
next Execute the next line within the current stack frame. ステップの次に移動するが、内部処理には入らない(ステップオーバー)
step Step execution into the next line or method. ステップの次に移動するが、内部処理に入る(ステップイン)
up Move current frame up. レシーバ呼び出し部分に戻る
Pry-byebug (v3.7.0)
exit-all End the current pry session.
エイリアスを作成してコマンド短縮
.pryrc
if defined?(PryByebug)
Pry.commands.alias_command 's', 'step'
Pry.commands.alias_command 'n', 'next'
Pry.commands.alias_command 'f', 'finish'
Pry.commands.alias_command 'c', 'continue'
end
pry-doc(rubygems)
show-method コマンドで C で書かれたコードやドキュメントも出力できるようになる
show-method は Pry のコマンドで通常は Ruby で書かれたコードやドキュメントのみ出力できる