0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VSCode Ruby LSPでrspecのテストを実行する

Last updated at Posted at 2025-09-16

やりたいこと

VSCodeの Run in terminal でrspecのテストを実行したい。
スクリーンショット 2025-09-17 4.27.16.png

※CodeLensを使わず、カーソル位置を対象にRSpec実行するだけでよければ、下記の方が簡単。

手順

1. VSCode拡張Ruby LSPをインストール

2. カスタムのGemfileをセットアップ

任意の場所にGemfile用ディレクトリを作成する:

$ mkdir {Gemfile用ディレクトリ}
$ cd {Gemfile用ディレクトリ}
$ rbenv local 3.3.8  # 自分の場合はこのバージョン

{Gemfile用ディレクトリ}にGemfileを作成:

# frozen_string_literal: true

source 'http://rubygems.org'

gem 'ruby-lsp'
gem 'ruby-lsp-rails'
gem 'ruby-lsp-rspec'

{Gemfile用ディレクトリ}内にgemをインストール:

$ bundle config path vendor
$ bundle install

3. VSCodeの設定

  "rubyLsp.bundleGemfile": "{Gemfile用ディレクトリ}/Gemfile",
  "rubyLsp.addonSettings": {
    "Ruby LSP RSpec": {
      "rspecCommand": "bundle exec rspec -I {Gemfile用ディレクトリ}/vendor/ruby/3.3.0/gems/ruby-lsp-0.26.1/lib/"
    }
  },

解説

Ruby LSPはプロジェクトのGemfileと.ruby-lsp/Gemfileをマージした状態で起動される。参考
そのため、プロジェクトのGemfileにgem 'ruby-lsp'を記述する必要はない。

Ruby LSP RSpecはRuby LSPのアドオンである。
VSCodeのRuby LSP拡張をインストールしただけではインストールされない。
そこで、rubyLsp.bundleGemfileによりカスタムのGemfileを指定する。参考

Run in terminal をするとbundle exec rspecが実行される。これは(マージされていない)プロジェクトのGemfileの状態で実行されるため、{Gemfile用ディレクトリ}内のファイルを読み込めない。そこでrspecCommand-Iにより$LOAD_PATHを追加している。

VSCode Ruby LSPの全設定

今回に関係ないだろうものも含めて全設定を載せておく。

  "rubyLsp.rubyVersionManager": {
    "identifier": "rbenv"
  },
  "rubyLsp.customRubyCommand": "export PATH={ホーム}/.rbenv/versions/3.3.8/bin:$PATH",
  "rubyLsp.bundleGemfile": "{ホーム}/w/ruby-lsp/Gemfile",
  "rubyLsp.addonSettings": {
    "Ruby LSP RSpec": {
      "rspecCommand": "bundle exec rspec -I ~/w/ruby-lsp/vendor/ruby/3.3.0/gems/ruby-lsp-0.26.1/lib/"
    }
  },
  "rubyLsp.enabledFeatures": {
    "codeActions": true,
    "diagnostics": true,
    "documentHighlights": true,
    "documentLink": true,
    "documentSymbols": true,
    "foldingRanges": true,
    "formatting": true,
    "hover": true,
    "inlayHint": true,
    "onTypeFormatting": true,
    "selectionRanges": true,
    "semanticHighlighting": true,
    "completion": true,
    "codeLens": true,
    "definition": false,
    "workspaceSymbol": true,
    "signatureHelp": true,
    "typeHierarchy": true,
    "references": true
  },
  "rubyLsp.featureFlags": {
    "all": true
  },
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?