Skip to content

Commit

Permalink
Merge pull request #846 from jfragoulis/factorybot/factoryclassname/e…
Browse files Browse the repository at this point in the history
…xclude-ruby-builtins

Fix `FactoryBot/FactoryClassName` to ignore `Hash` and `OpenStruct`
  • Loading branch information
Darhazer authored Dec 13, 2019
2 parents b52f456 + 0cf71ba commit 49d616e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Master (Unreleased)

* Improve message and description of `FactoryBot/FactoryClassName`. ([@ybiquitous][])
* Fix `FactoryBot/FactoryClassName` to ignore `Hash` and `OpenStruct`. ([@jfragoulis][])

## 1.37.0 (2019-11-25)

Expand Down
9 changes: 9 additions & 0 deletions lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ module FactoryBot
class FactoryClassName < Cop
MSG = "Pass '%<class_name>s' string instead of `%<class_name>s` " \
'constant.'
ALLOWED_CONSTANTS = %w[Hash OpenStruct].freeze

def_node_matcher :class_name, <<~PATTERN
(send _ :factory _ (hash <(pair (sym :class) $(const ...)) ...>))
PATTERN

def on_send(node)
class_name(node) do |cn|
next if allowed?(cn.const_name)

add_offense(cn, message: format(MSG, class_name: cn.const_name))
end
end
Expand All @@ -38,6 +41,12 @@ def autocorrect(node)
corrector.replace(node.loc.expression, "'#{node.source}'")
end
end

private

def allowed?(const_name)
ALLOWED_CONSTANTS.include?(const_name)
end
end
end
end
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/rspec/factory_bot/factory_class_name_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@
end
RUBY
end

it 'ignores passing Hash' do
expect_no_offenses(<<~RUBY)
factory :foo, class: Hash do
end
RUBY
end

it 'ignores passing OpenStruct' do
expect_no_offenses(<<~RUBY)
factory :foo, class: OpenStruct do
end
RUBY
end
end

context 'when not passing block' do
Expand Down

0 comments on commit 49d616e

Please sign in to comment.