Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cop idea: Warn when creating global shared contexts/examples within tests #1814

Open
opal-storypark opened this issue Feb 23, 2024 · 1 comment

Comments

@opal-storypark
Copy link

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.

@pirj
Copy link
Member

pirj commented Feb 23, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants