Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0cf71ba

Browse files
committed
Fix FactoryBot/FactoryClassName to ignore Hash and OpenStruct
Hash and OpenStruct are used in factories widely. The factory should not force them into strings as they are built in language objects.
1 parent b52f456 commit 0cf71ba

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Master (Unreleased)
44

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

78
## 1.37.0 (2019-11-25)
89

lib/rubocop/cop/rspec/factory_bot/factory_class_name.rb

+9
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,16 @@ module FactoryBot
2222
class FactoryClassName < Cop
2323
MSG = "Pass '%<class_name>s' string instead of `%<class_name>s` " \
2424
'constant.'
25+
ALLOWED_CONSTANTS = %w[Hash OpenStruct].freeze
2526

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

3031
def on_send(node)
3132
class_name(node) do |cn|
33+
next if allowed?(cn.const_name)
34+
3235
add_offense(cn, message: format(MSG, class_name: cn.const_name))
3336
end
3437
end
@@ -38,6 +41,12 @@ def autocorrect(node)
3841
corrector.replace(node.loc.expression, "'#{node.source}'")
3942
end
4043
end
44+
45+
private
46+
47+
def allowed?(const_name)
48+
ALLOWED_CONSTANTS.include?(const_name)
49+
end
4150
end
4251
end
4352
end

spec/rubocop/cop/rspec/factory_bot/factory_class_name_spec.rb

+14
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@
4949
end
5050
RUBY
5151
end
52+
53+
it 'ignores passing Hash' do
54+
expect_no_offenses(<<~RUBY)
55+
factory :foo, class: Hash do
56+
end
57+
RUBY
58+
end
59+
60+
it 'ignores passing OpenStruct' do
61+
expect_no_offenses(<<~RUBY)
62+
factory :foo, class: OpenStruct do
63+
end
64+
RUBY
65+
end
5266
end
5367

5468
context 'when not passing block' do

0 commit comments

Comments
 (0)