Remote debugging in Rails 7

posted by Ayush Newatia
23 September, 2022



This post was extracted and adapted from The Rails and Hotwire Codex.

Rails 7 includes the official Ruby debugger. It also uses Foreman to orchestrate multiple processes in development. This way you can run the Rails server along with processes to watch and compile your frontend assets using a single command.

Annoyingly, this makes debugging trickier. You can’t just add a breakpoint in your app and run commands in the console. The same Terminal window is running multiple processes, so won’t always be interactive.

The debug gem supports remote debugging which is useful in such cases. Using this setup, an external, independent debugger process attaches to another debuggee Ruby process.

Enable remote debugging in your Rails app by adding the below lines to your application.rb.

require "rails/all"

if defined?(Rails::Server) && Rails.env.development?
  require "debug/open_nonstop"
end

# ...

We verify the Rails environment is development and that the Rails::Serverconstant is defined before enabling remote debugging. The latter check ensures remote debugging is enabled only when the app runs in the context of a web server. It shouldn’t be enabled in other contexts like the Rails console or a background job processor like Sidekiq.

Now when you start the Rails server in development, the debug gem will open a UNIX domain socket which the debugger process can connect to.

Start the server using bin/dev and in another Terminal window, run:

$ bundle exec rdbg -a

If the Rails server is the only debuggable process running (it should be), the debugger will connect. You can add then breakpoints in the app and run commands in the debugger process!

Ctrl+D will exit the debugger and leave the Rails server running. I recommend doing this after you’ve finished debugging. Check out the docs for the full list of available commands: https://github.com/ruby/debug#control-flow.

NOTE : You can also use the statement require "debug/open" instead of require "debug/open_nonstop". The downside here is the program will be paused on launch until you attach the debugger and continue it. This can get very fiddly given how often the server needs to be restarted during development.

If you liked this post, check out my book, The Rails and Hotwire Codex, to level-up your Rails and Hotwire skills!