やりたいこと
VSCodeの Run in terminal
でrspecのテストを実行したい。
※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
},