Debugging Ruby projects in Visual Studio Code

This article explain how configure Visual Studio Code debugger for your Ruby project. After setup you will be able to debug your code like an in RubyMine.

Motivation

When I tried to configure Ruby debugging for the first time, I read a great number of articles and tutorials and dont found how get things done when Ruby installed through rvm or rbenv. The purpose of this article is to fill this gap and offer simple and obvious way to setup debug for your projects.

Table of Contents

Requirements

  1. VS Code with plugin.
  2. rbenv, Ruby and Bundler.

Project setup

Dependencies

Add to your Gemfile:

group :development, :test do
  gem "ruby-debug-ide", require: false
  gem "debase", require: false
end

and run bundle install

Ruby version

Create .ruby-version file in root of project if it not already exists.

$ echo "2.6.3" > .ruby-version

Binstubs

Generate bundler bintubs which will be very useful later:

$ bundle binstubs bundler ruby-debug-ide

Binstub for test library (rspec for example):

$ bundle binstubs rspec-core

After all in bin folder you will see 4 new files: rdebug-ide, gdb_wrapper, bundle, rspec, which will be used in VS Code configuration files.

Launch

Copy to .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Start rails server",
      "type": "Ruby",
      "request": "launch",
      "cwd": "${workspaceRoot}",
      "program": "${workspaceRoot}/bin/rails",
      "useBundler": true,
      "pathToBundler": "${workspaceRoot}/bin/bundle",
      "showDebuggerOutput": true,
      "pathToRDebugIDE": "/${workspaceRoot}/bin/rdebug-ide",
      "args": ["s"]
    },
    {
      "name": "Run tests",
      "type": "Ruby",
      "request": "launch",
      "cwd": "${workspaceRoot}",
      "program": "${workspaceRoot}/bin/rspec",
      "useBundler": true,
      "pathToBundler": "${workspaceRoot}/bin/bundle",
      "showDebuggerOutput": true,
      "pathToRDebugIDE": "/${workspaceRoot}/bin/rdebug-ide",
      "args": []
    }
  ]
}

Result

We configure debug, it depends only on project binstubs and works as expected with rbenv. Press CTRL+SHIFT+D, choose configuration and fix bugs faster!

P.S. If you want to setup linters, auto completion and many other cool things check vscode-ruby plugin homepage