如何解决Sorbet在Rails项目中无法解析常量RSpec的问题?
Got it, let's tackle this Sorbet error you're seeing after adding RSpec to your Rails project. The core issue is that Sorbet doesn't automatically recognize RSpec's constants or know where to look for its type definitions out of the box. Here's how to fix it step by step:
Generate RSpec type definitions (RBIs) for Sorbet
Sorbet relies on RBI files to understand external gem constants. Run this command to generate RBIs specifically for RSpec gems:srb rbi gems rspec-core rspec-expectations rspec-mocksAlternatively, if you want to generate RBIs for all installed gems at once, use:
srb rbi gemsThis creates the necessary type stubs so Sorbet knows what
RSpecis.Update Sorbet's config to include the spec directory
Open yourconfig/sorbet/configfile and add the--dir specflag. This tells Sorbet to scan and process files in the spec directory, which it might be ignoring by default. Your config should look something like this:--dir app --dir config --dir spec --dir lib --typed trueVerify your spec_helper.rb has the correct type annotation
At the top ofspec/spec_helper.rb, make sure you have a type annotation (even# typed: trueworks). This tells Sorbet to process the file with type checking:# typed: true require 'rspec/rails' RSpec.configure do |config| # ... your config here endOptional: Temporary workaround if issues persist
If you need a quick fix while sorting out the RBIs or config, you can wrap the RSpec reference inT.unsafeto tell Sorbet to skip type checking for that line:T.unsafe(RSpec).configure do |config| # ... endNote: This is a band-aid solution—focus on the first two steps for a proper fix.
After running these steps, re-run srb tc and the "Unable to resolve constant RSpec" error should be gone.
内容的提问来源于stack exchange,提问作者steel

