June 6, 2016

Add binding.pry breakpoint dynamically with pry-byebug

When debugging if you want to check at some lines where you forget to put the binding.pry, you could use some help from pry-byebug's break points feature.

You can set and adjust breakpoints directly from a Pry session using the break command:

break SomeClass#run            # Break at the start of `SomeClass#run`.
break app/models/user.rb:15    # Break at line 15 in user.rb.

Please bear with me with this example as a showcase.

scenario "Guest can't view draft post" do
  post = create(:post, title: 'Vim', published_at: nil)
  visit post_path(post)
  expect(page).not_to have_content('Vim')

Suppose you put the first binding.pry there to check the creation of post, then somehow you also want to check what's going on in the controller, normally you would stop/finish the spec and drop the binding.pry to controller and rerun the spec. With pry-byebug you could set the breakpoint in the runtime: when the execution is stopped before the visit post_path(post)

[1] pry(#<RSpec::ExampleGroups::Posts>)> break PostsController#show

  Breakpoint 1: PostsController#show (Enabled)

  10: def show
  11: end

Now the breakpoint is set, if you continue the spec then it'll stop at the posts#show action.

This is also very useful when you check some codebase you're not familiar with like gems, during the debugging you also want to check some local variables inside a block or so, with the break command now you don't need to make changes to the library and restart your rails server.

Share on Twitter Share the post
Qihuan Piao

Qihuan Piao

(aka kinopyo) is Chinese based in Tokyo. Software writer. He shares stories inspired him in this blog. His infamous line - "I feel calm when I kill those monsters, or people (in game)" shocks his friends deeply.

He also writes in Japanese and Chinese.