How to Debug Rails Applications and Tests in VS Code

Debugging is an essential yet often tedious task for software developers. While scattering print statements throughout your code is a common approach, using a proper debugger is far more efficient. For Ruby on Rails developers, VS Code offers robust debugging capabilities through the Ruby LSP extension, making it easier to identify and resolve issues in your application.

Why Debug in VS Code?

Rails applications can be debugged using tools like the debug gem for terminal-based debugging or the web-console gem for browser-based debugging, as outlined in the official Rails documentation. However, debugging directly within your IDE provides a more seamless experience. With the Ruby LSP extension in VS Code, you can set breakpoints, inspect variables, and view the call stack, streamlining the process of diagnosing and fixing issues.

Setting Up Debugging for Rails Applications

To debug a running Rails application in VS Code, you need to configure a launch configuration. Create a launch.json file in the .vscode directory of your project with the following content:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "ruby_lsp",
      "request": "launch",
      "name": "Debug Rails Server",
      "program": "${workspaceFolder}/bin/rails server"
    }
  ]
}

Once configured, navigate to the “Run and Debug” panel in VS Code to start the Rails server in debug mode. You can then set breakpoints to pause execution and inspect the application’s state, making it easier to troubleshoot complex issues.

Debugging Rails Tests

The Ruby LSP extension natively supports debugging with the standard Rails testing framework. You can run and debug test cases directly from the “Testing” panel in VS Code.

For projects using RSpec, additional setup is required. The Ruby LSP extension does not support RSpec out-of-the-box, but you can add the ruby-lsp-rspec addon to enable this functionality. Install the addon by adding it to your Gemfile:

group :development, :test do
  gem "ruby-lsp-rspec", require: false
end

After installing the gem and restarting the Ruby LSP server, you can run and debug RSpec tests directly from the “Testing” panel, just like standard Rails tests.

Summary

Debugging Ruby on Rails applications in VS Code with the Ruby LSP extension offers a powerful and intuitive way to diagnose issues. By setting up a launch configuration, you can debug your Rails server, and with the ruby-lsp-rspec addon, you can extend this capability to RSpec tests. This approach eliminates the need for scattered print statements, making your debugging process more efficient.