Cop idea: Warn when creating global shared contexts/examples within tests
opal-storypark opened this issue · 1 comments
We've recently found that a bunch of our test files are generating warnings because they use RSpec.shared_example
& RSpec.shared_context
with the same context name in multiple test files. Ideally we'd like to have a cop that detects the use of these global shared context helpers within either test blocks, or better yet test files.
I'd imagine it could come with an unsafe fix. But we wouldn't be able to auto-fix all of the occurrences because changing from RSpec.shared_context
to shared_context
changes the scoping of the shared context which might break things(especially if the original developer mis-indented some of the contexts).
Proposed lint:
spec/something_spec.rb
RSpec.describe "something" do
# bad
RSpec.shared_example "some example" do
# ...
end
RSpec.shared_context "some example" do
# ...
end
# good
shared_example "some example" do
# ...
end
shared_context "some example" do
# ...
end
end
Ideal cop
And ideally it would also catch global shared examples being defined at the top of a test file.
spec/something_spec.rb
# bad
RSpec.shared_example "some example" do
# ...
end
# ...
RSpec.describe "something" do
# ...
end
But wouldn't catch something like this:
spec/spec_helper.rb
# good
RSpec.shared_example "some example" do
# ...
end
Alternatives
For a subset of these issues we can use the existing RSpec warning which is printed whenever a shared example/context is redefined, but this doesn't catch single global definitions within tests.
Thanks for reporting!
This looks like an RSpec bug to me. RSpec won’t allow for RSpec.describe
inside an RSpec.describe
.
This should issue a warning, and I believe should be restricted in a major version there.
We could detect this, but our non-goals are to detect/fix things that RSpec has warnings for.
I suggest opening an issue in rspec-core, or even better sending a PR.