Home > Mobile >  RSpec navigatable it_behaves_like/shared_examples using LSP
RSpec navigatable it_behaves_like/shared_examples using LSP

Time:06-04

I have a legacy project that uses shared_examples feature a lot and it is very inconvenient to navigate between actual specs and shared_examples implementation.

For now, the only way to do it is to search globally within a project using "some example" example name.

RSpec.shared_examples "some example" do |parameter|
  let(:something) { parameter }

  it "uses the given parameter" do
    expect(something).to eq(parameter)
  end
end

RSpec.describe SomeClass do
  # "some example" has to become *something*
  # I can click and navigate to(jump-to-definition)
  include_examples "some example", "parameter1"
end

I would like to use LSP/Solargraph for this kind of navigation.

Perhaps anyone did this before and willing to share how they did it?

CodePudding user response:

This turned out simpler than I expected.

Just extract your example name as a string constant and put it somewhere next to RSpec.shared_examples implementation.

# spec/support/shared_examples.rb
# in case you prefer one-liner use:
# RSpec.shared_examples(A_COLLECTION = 'a collection') do
# otherwise:

A_COLLECTION = 'a collection'
RSpec.shared_examples A_COLLECTION do
  let(:collection) { described_class.new([7, 2, 4]) }

  context 'initialized with 3 items' do
    it 'says it has three items' do
      expect(collection.size).to eq(3)
    end
  end
end
# spec/array_spec.rb
RSpec.describe Array do
  it_behaves_like A_COLLECTION
end

HINT: In case it doesn't work for you, check .solargraph.yml config which excludes "spec/**/*" from indexing by default.

  • Related