Skip to content

Commit

Permalink
FEATURE: Add autocorrect to the FabricatorShorthand cop
Browse files Browse the repository at this point in the history
  • Loading branch information
Flink committed Feb 29, 2024
1 parent f1a646e commit c5e33d9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
20 changes: 15 additions & 5 deletions lib/rubocop/cop/discourse/fabricator_shorthand.rb
Expand Up @@ -26,25 +26,35 @@ module Discourse
# # good
# fab!(:another_user) { Fabricate(:user) }
class FabricatorShorthand < Base
extend AutoCorrector
include IgnoredNode

def_node_matcher :offending_fabricator?, <<-MATCHER
(block
(send nil? :fab!
$(send nil? :fab!
(sym $_identifier))
(args)
(send nil? :Fabricate
(sym $_identifier)))
MATCHER

def on_block(node)
offending_fabricator?(node) do |identifier|
add_offense(node, message: message(identifier))
offending_fabricator?(node) do |expression, _identifier|
add_offense(
node,
message: message(expression.source)
) do |corrector|
next if part_of_ignored_node?(node)
corrector.replace(node, expression.source)
end
ignore_node(node)
end
end

private

def message(identifier)
"Use the fabricator shorthand: `fab!(:#{identifier})`"
def message(expression)
"Use the fabricator shorthand: `#{expression}`"
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion rubocop-discourse.gemspec
Expand Up @@ -2,7 +2,7 @@

Gem::Specification.new do |s|
s.name = "rubocop-discourse"
s.version = "3.7.0"
s.version = "3.7.1"
s.summary = "Custom rubocop cops used by Discourse"
s.authors = ["Discourse Team"]
s.license = "MIT"
Expand Down
15 changes: 15 additions & 0 deletions spec/lib/rubocop/cop/fabricator_shorthand_spec.rb
Expand Up @@ -31,4 +31,19 @@
end
RUBY
end

it "supports autocorrect" do
expect_offense(<<~RUBY)
RSpec.describe "Foo" do
fab!(:foo) { Fabricate(:foo) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Discourse/FabricatorShorthand: Use the fabricator shorthand: `fab!(:foo)`
end
RUBY

expect_correction(<<~RUBY)
RSpec.describe "Foo" do
fab!(:foo)
end
RUBY
end
end

0 comments on commit c5e33d9

Please sign in to comment.