rubocop-munra 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -0
  3. data/README.md +11 -1
  4. data/config/default.yml +101 -1
  5. data/lib/rubocop/cop/munra/00_model_scope_names.rb +42 -0
  6. data/lib/rubocop/cop/munra/00_model_spec_section_checks.rb +71 -0
  7. data/lib/rubocop/cop/munra/00_rspec_helpers.rb +26 -3
  8. data/lib/rubocop/cop/munra/00_transaction_block_mixin.rb +7 -6
  9. data/lib/rubocop/cop/munra/address_fields_order.rb +66 -0
  10. data/lib/rubocop/cop/munra/address_state_select.rb +3 -3
  11. data/lib/rubocop/cop/munra/admin_policy.rb +55 -8
  12. data/lib/rubocop/cop/munra/brazilian_state_inclusion.rb +67 -0
  13. data/lib/rubocop/cop/munra/builtin_validation_options.rb +24 -6
  14. data/lib/rubocop/cop/munra/digits_only_attributes.rb +103 -0
  15. data/lib/rubocop/cop/munra/email_format.rb +21 -26
  16. data/lib/rubocop/cop/munra/flash_success_locale_name.rb +30 -25
  17. data/lib/rubocop/cop/munra/flash_success_name.rb +2 -2
  18. data/lib/rubocop/cop/munra/full_error_messages.rb +3 -6
  19. data/lib/rubocop/cop/munra/let_layout.rb +9 -2
  20. data/lib/rubocop/cop/munra/literal_expectation.rb +68 -0
  21. data/lib/rubocop/cop/munra/model_spec_structure.rb +156 -0
  22. data/lib/rubocop/cop/munra/named_subject_layout.rb +4 -6
  23. data/lib/rubocop/cop/munra/no_current_date_in_system_spec.rb +37 -0
  24. data/lib/rubocop/cop/munra/no_human_attribute_name.rb +1 -1
  25. data/lib/rubocop/cop/munra/no_inline_validation.rb +1 -1
  26. data/lib/rubocop/cop/munra/no_leading_dot.rb +1 -1
  27. data/lib/rubocop/cop/munra/no_mixed_example_siblings.rb +57 -0
  28. data/lib/rubocop/cop/munra/no_shared_examples.rb +9 -4
  29. data/lib/rubocop/cop/munra/one_example_per_context.rb +54 -0
  30. data/lib/rubocop/cop/munra/policy_blank_deny.rb +133 -0
  31. data/lib/rubocop/cop/munra/service_object.rb +14 -6
  32. data/lib/rubocop/cop/munra/validations_before_callbacks.rb +80 -0
  33. data/lib/rubocop/munra/plugin.rb +1 -1
  34. data/lib/rubocop/munra/version.rb +1 -3
  35. metadata +14 -19
  36. data/.github/workflows/ci.yml +0 -29
  37. data/.github/workflows/docs.yml +0 -90
  38. data/.ruby-version +0 -1
  39. data/AGENTS.md +0 -101
  40. data/CODE_OF_CONDUCT.md +0 -10
  41. data/Rakefile +0 -42
  42. data/antora-playbook.yml +0 -22
  43. data/docs/antora.yml +0 -5
  44. data/docs/modules/ROOT/nav.adoc +0 -5
  45. data/docs/modules/ROOT/pages/cops.adoc +0 -2
  46. data/docs/modules/ROOT/pages/cops_munra.adoc +0 -1026
  47. data/docs/modules/ROOT/pages/index.adoc +0 -11
  48. data/docs/modules/ROOT/pages/installation.adoc +0 -50
  49. data/docs/modules/ROOT/pages/usage.adoc +0 -98
  50. data/docs/usage.md +0 -29
  51. data/package-lock.json +0 -1930
  52. data/package.json +0 -12
  53. data/sig/rubocop/munra.rbs +0 -6
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ # `address_state` (or the configured Attribute) must validate inclusion in
4
+ # `BrazilianState::CODES` (or the configured InclusionConstant).
5
+ #
6
+ # @example
7
+ # # bad
8
+ # class Foo < ApplicationRecord
9
+ # validates :address_state, presence: true
10
+ # end
11
+ #
12
+ # # good
13
+ # class Foo < ApplicationRecord
14
+ # validates :address_state, presence: true, inclusion: { in: BrazilianState::CODES }
15
+ # end
16
+ class RuboCop::Cop::Munra::BrazilianStateInclusion < RuboCop::Cop::Base
17
+ MSG = '`%<attribute>s` must validate inclusion in `%<inclusion_constant>s`.'
18
+
19
+ RESTRICT_ON_SEND = [:validates].freeze
20
+
21
+ def on_send(node)
22
+ return unless validates_state_attribute?(node)
23
+ return if state_inclusion?(node)
24
+
25
+ add_offense(node, message: format(MSG, attribute: state_attribute, inclusion_constant: inclusion_constant))
26
+ end
27
+
28
+ private
29
+
30
+ def state_attribute
31
+ cop_config.fetch('Attribute', 'address_state').to_sym
32
+ end
33
+
34
+ def inclusion_constant
35
+ cop_config.fetch('InclusionConstant', 'BrazilianState::CODES')
36
+ end
37
+
38
+ def validates_state_attribute?(node)
39
+ attribute = state_attribute
40
+ node.arguments.any? { |arg| arg.sym_type? && arg.value == attribute }
41
+ end
42
+
43
+ def state_inclusion?(node)
44
+ node.arguments.any? { |arg| inclusion_option?(arg) }
45
+ end
46
+
47
+ def inclusion_option?(arg)
48
+ return false unless arg.hash_type?
49
+
50
+ arg.pairs.any? { |pair| inclusion_pair?(pair) }
51
+ end
52
+
53
+ def inclusion_pair?(pair)
54
+ return false unless pair.key.sym_type? && pair.key.value == :inclusion
55
+
56
+ inclusion_value?(pair.value)
57
+ end
58
+
59
+ def inclusion_value?(value)
60
+ return false unless value.hash_type?
61
+
62
+ constant = inclusion_constant
63
+ value.pairs.any? do |inclusion_pair|
64
+ inclusion_pair.value.const_type? && inclusion_pair.value.source == constant
65
+ end
66
+ end
67
+ end
@@ -15,9 +15,9 @@
15
15
  # validates_with CustomValidator
16
16
  class RuboCop::Cop::Munra::BuiltinValidationOptions < RuboCop::Cop::Base
17
17
  # Placeholder text for readers; not passed through Kernel#format.
18
- MSG = 'Use `validates_with` for custom validations instead of `validates :attr, %{key}: true`.' # rubocop:disable Style/FormatStringToken
18
+ MSG = 'Use `validates_with` for custom validations instead of `validates :attr, %{key}: true`.'
19
19
 
20
- RESTRICT_ON_SEND = %i[validates].freeze
20
+ RESTRICT_ON_SEND = [:validates].freeze
21
21
 
22
22
  def on_send(node)
23
23
  validation_keys(node).each do |key_pair|
@@ -32,10 +32,28 @@ class RuboCop::Cop::Munra::BuiltinValidationOptions < RuboCop::Cop::Base
32
32
  def allowed_keys
33
33
  Array(
34
34
  cop_config.fetch(
35
- 'AllowedKeys', %w[
36
- presence format uniqueness length numericality inclusion exclusion
37
- comparison acceptance confirmation absence
38
- allow_nil allow_blank if unless on strict message scope with conditions
35
+ 'AllowedKeys', [
36
+ 'presence',
37
+ 'format',
38
+ 'uniqueness',
39
+ 'length',
40
+ 'numericality',
41
+ 'inclusion',
42
+ 'exclusion',
43
+ 'comparison',
44
+ 'acceptance',
45
+ 'confirmation',
46
+ 'absence',
47
+ 'allow_nil',
48
+ 'allow_blank',
49
+ 'if',
50
+ 'unless',
51
+ 'on',
52
+ 'strict',
53
+ 'message',
54
+ 'scope',
55
+ 'with',
56
+ 'conditions'
39
57
  ]
40
58
  )
41
59
  ).map(&:to_sym)
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Digit attributes must use `normalizes_digits_only` instead of hand-written
4
+ # `before_validation` callbacks.
5
+ #
6
+ # When a model validates a configured digit attribute (`cpf`, `phone`,
7
+ # `address_zip_code` by default), it must also call the configured normalizer
8
+ # method for that attribute. Manual `before_validation :normalize_*` callbacks
9
+ # are flagged as well.
10
+ #
11
+ # @example
12
+ # # bad
13
+ # class Foo < ApplicationRecord
14
+ # validates :cpf, presence: true
15
+ # before_validation :normalize_cpf
16
+ # end
17
+ #
18
+ # # bad
19
+ # class Foo < ApplicationRecord
20
+ # validates :cpf, presence: true
21
+ # end
22
+ #
23
+ # # good
24
+ # class Foo < ApplicationRecord
25
+ # validates :cpf, presence: true
26
+ # normalizes_digits_only :cpf
27
+ # end
28
+ class RuboCop::Cop::Munra::DigitsOnlyAttributes < RuboCop::Cop::Base
29
+ MSG_NORMALIZE = 'Use `%<normalizer>s` for `:%<attr>s` instead of manual callbacks.'
30
+ MSG_MISSING = 'Include `%<normalizer>s :%<attr>s` when validating `:%<attr>s`.'
31
+
32
+ def on_class(node)
33
+ digit_attrs = digit_attributes_in_class(node)
34
+ return if digit_attrs.empty?
35
+
36
+ check_manual_callbacks(node)
37
+ check_normalizes_digits_only(node, digit_attrs)
38
+ end
39
+
40
+ private
41
+
42
+ def digit_attributes
43
+ cop_config.fetch('Attributes', ['cpf', 'phone', 'address_zip_code']).map(&:to_sym)
44
+ end
45
+
46
+ def normalizer_method
47
+ cop_config.fetch('NormalizerMethod', 'normalizes_digits_only')
48
+ end
49
+
50
+ def normalizer_method_name
51
+ normalizer_method.to_sym
52
+ end
53
+
54
+ def manual_callback_pattern
55
+ names = digit_attributes.map { |attr| Regexp.escape(attr.to_s) }.join('|')
56
+ /\Anormalize_(?:#{names})\z/
57
+ end
58
+
59
+ def digit_attributes_in_class(node)
60
+ digit_attributes.select do |attr|
61
+ model_validates_attribute?(node, attr)
62
+ end
63
+ end
64
+
65
+ def model_validates_attribute?(node, attr)
66
+ node.each_descendant(:send).any? do |send|
67
+ next false unless send.method_name == :validates
68
+
69
+ send.arguments.any? { |arg| arg.sym_type? && arg.value == attr }
70
+ end
71
+ end
72
+
73
+ def check_manual_callbacks(node)
74
+ pattern = manual_callback_pattern
75
+ node.each_descendant(:send) do |send|
76
+ next unless send.method_name == :before_validation
77
+
78
+ send.arguments.select(&:sym_type?).each do |symbol|
79
+ next unless symbol.value.to_s.match?(pattern)
80
+
81
+ add_offense(send, message: format(MSG_NORMALIZE, attr: symbol.value, normalizer: normalizer_method))
82
+ end
83
+ end
84
+ end
85
+
86
+ def check_normalizes_digits_only(node, digit_attrs)
87
+ normalized = normalized_digit_attributes(node)
88
+ digit_attrs.each do |attr|
89
+ next if normalized.include?(attr)
90
+
91
+ add_offense(node.identifier, message: format(MSG_MISSING, attr: attr, normalizer: normalizer_method))
92
+ end
93
+ end
94
+
95
+ def normalized_digit_attributes(node)
96
+ method_name = normalizer_method_name
97
+ node.each_descendant(:send).flat_map do |send|
98
+ next [] unless send.method_name == method_name
99
+
100
+ send.arguments.select(&:sym_type?).map(&:value)
101
+ end
102
+ end
103
+ end
@@ -26,9 +26,10 @@ class RuboCop::Cop::Munra::EmailFormat < RuboCop::Cop::Base
26
26
  MSG = 'Models with an %<attribute>s attribute need `validates_with %<validator>s` (unless using Devise :%<devise_module>s).'
27
27
 
28
28
  def on_class(node)
29
- return unless model_with_email?(node)
30
- return if devise_validatable?(node)
31
- return if validates_with_email_format?(node)
29
+ flags = class_flags(node)
30
+ return unless flags[:has_email]
31
+ return if flags[:devise_validatable]
32
+ return if flags[:email_validator]
32
33
 
33
34
  add_offense(node.identifier, message: format(MSG, **message_interpolations))
34
35
  end
@@ -55,34 +56,28 @@ class RuboCop::Cop::Munra::EmailFormat < RuboCop::Cop::Base
55
56
  }
56
57
  end
57
58
 
58
- def model_with_email?(node)
59
- attribute = email_attribute
60
- node.each_descendant(:send).any? do |send|
61
- next false unless send.method_name == :validates
62
-
63
- send.arguments.any? do |arg|
64
- arg.sym_type? && arg.value == attribute
65
- end
66
- end
59
+ def class_flags(node)
60
+ flags = { has_email: false, devise_validatable: false, email_validator: false }
61
+ node.each_descendant(:send) { |send| update_class_flags(flags, send) }
62
+ flags
67
63
  end
68
64
 
69
- def devise_validatable?(node)
70
- skip_module = devise_skip_module
71
- node.each_descendant(:send).any? do |send|
72
- next false unless send.method_name == :devise
73
-
74
- send.arguments.any? { |arg| arg.sym_type? && arg.value == skip_module }
65
+ def update_class_flags(flags, send)
66
+ case send.method_name
67
+ when :validates
68
+ flags[:has_email] ||= argument_symbol?(send, email_attribute)
69
+ when :devise
70
+ flags[:devise_validatable] ||= argument_symbol?(send, devise_skip_module)
71
+ when :validates_with
72
+ flags[:email_validator] ||= validates_with_constant?(send, email_validator)
75
73
  end
76
74
  end
77
75
 
78
- def validates_with_email_format?(node)
79
- validator = email_validator
80
- node.each_descendant(:send).any? do |send|
81
- next false unless send.method_name == :validates_with
76
+ def argument_symbol?(send, value)
77
+ send.arguments.any? { |arg| arg.sym_type? && arg.value == value }
78
+ end
82
79
 
83
- send.arguments.any? do |arg|
84
- arg.const_type? && arg.source == validator
85
- end
86
- end
80
+ def validates_with_constant?(send, validator)
81
+ send.arguments.any? { |arg| arg.const_type? && arg.source == validator }
87
82
  end
88
83
  end
@@ -27,35 +27,16 @@ class RuboCop::Cop::Munra::FlashSuccessLocaleName < RuboCop::Cop::Base
27
27
  MSG = 'Controller flash success messages must include `%<interpolation>s`.'
28
28
 
29
29
  # YAML locales are not valid Ruby — use `on_other_file`.
30
- # rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
31
30
  def on_other_file
32
- section_key = locale_section_key
33
- entry_key = locale_entry_key
31
+ state = { in_section: false, section_indent: nil }
32
+ pattern = success_line_pattern(locale_entry_key)
34
33
  interpolation = required_interpolation
35
- success_line = success_line_pattern(entry_key)
36
- in_section = false
37
- section_indent = nil
38
34
 
39
35
  processed_source.raw_source.each_line.with_index(1) do |line, line_number|
40
- indent = line[/^\s*/].length
36
+ update_section_state(state, line)
37
+ next unless state[:in_section]
41
38
 
42
- if line.match?(/^\s*#{Regexp.escape(section_key)}:\s*$/)
43
- in_section = true
44
- section_indent = indent
45
- next
46
- end
47
-
48
- in_section = false if in_section && indent <= section_indent && line.match?(/^\s*\S/)
49
-
50
- next unless in_section
51
-
52
- match = success_line.match(line)
53
- next unless match
54
-
55
- value = match[:quoted] || match[:bare]
56
- next if value.include?(interpolation)
57
-
58
- add_offense(line_range(line_number), message: format(MSG, interpolation: interpolation))
39
+ check_success_line(line, line_number, pattern, interpolation)
59
40
  end
60
41
  end
61
42
 
@@ -70,10 +51,34 @@ class RuboCop::Cop::Munra::FlashSuccessLocaleName < RuboCop::Cop::Base
70
51
  end
71
52
 
72
53
  def required_interpolation
73
- # rubocop:disable-next Style/FormatStringToken -- I18n interpolation token, not Kernel#format
74
54
  cop_config.fetch('RequiredInterpolation', '%{name}')
75
55
  end
76
56
 
57
+ def update_section_state(state, line)
58
+ indent = line[/^\s*/].length
59
+
60
+ if line.match?(/^\s*#{Regexp.escape(locale_section_key)}:\s*$/)
61
+ state[:in_section] = true
62
+ state[:section_indent] = indent
63
+ return
64
+ end
65
+
66
+ return unless state[:in_section]
67
+ return unless indent <= state[:section_indent] && line.match?(/^\s*\S/)
68
+
69
+ state[:in_section] = false
70
+ end
71
+
72
+ def check_success_line(line, line_number, pattern, interpolation)
73
+ match = pattern.match(line)
74
+ return unless match
75
+
76
+ value = match[:quoted] || match[:bare]
77
+ return if value.include?(interpolation)
78
+
79
+ add_offense(line_range(line_number), message: format(MSG, interpolation: interpolation))
80
+ end
81
+
77
82
  def success_line_pattern(entry_key)
78
83
  /
79
84
  ^(?<indent>\s*)#{Regexp.escape(entry_key)}:\s*
@@ -16,7 +16,8 @@
16
16
  class RuboCop::Cop::Munra::FlashSuccessName < RuboCop::Cop::Base
17
17
  MSG = 'Flash success messages must include `%<key>s:` in the `I18n.t` / `t` call.'
18
18
 
19
- I18N_METHODS = %i[t translate].freeze
19
+ I18N_METHODS = [:t, :translate].freeze
20
+ RESTRICT_ON_SEND = I18N_METHODS
20
21
 
21
22
  def on_send(node)
22
23
  return unless i18n_success_without_name?(node)
@@ -35,7 +36,6 @@ class RuboCop::Cop::Munra::FlashSuccessName < RuboCop::Cop::Base
35
36
  cop_config.fetch('LocaleKeyFragment', 'success')
36
37
  end
37
38
 
38
- # rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
39
39
  def i18n_success_without_name?(node)
40
40
  return false unless i18n_call?(node)
41
41
 
@@ -16,8 +16,8 @@ class RuboCop::Cop::Munra::FullErrorMessages < RuboCop::Cop::Base
16
16
 
17
17
  MSG = 'Assert the full error message set with `eq`, not `include`.'
18
18
 
19
- RESTRICT_ON_SEND = %i[to].freeze
20
- ERRORS_METHODS = %i[errors messages full_messages].freeze
19
+ RESTRICT_ON_SEND = [:to].freeze
20
+ ERRORS_METHODS = [:errors, :messages, :full_messages].freeze
21
21
 
22
22
  def on_send(node)
23
23
  return unless errors_include_expectation?(node)
@@ -42,10 +42,7 @@ class RuboCop::Cop::Munra::FullErrorMessages < RuboCop::Cop::Base
42
42
  end
43
43
 
44
44
  def expect_send?(receiver)
45
- receiver.respond_to?(:send_type?) &&
46
- receiver.send_type? &&
47
- receiver.receiver.nil? &&
48
- receiver.method_name == :expect
45
+ receiver.respond_to?(:send_type?) && receiver.send_type? && receiver.receiver.nil? && receiver.method_name == :expect
49
46
  end
50
47
 
51
48
  def errors_accessor?(node)
@@ -138,11 +138,15 @@ class RuboCop::Cop::Munra::LetLayout < RuboCop::Cop::Base
138
138
 
139
139
  next_source = processed_source.lines[next_line - 1]
140
140
  return if next_source.strip.empty?
141
- return if next_source.strip == 'end'
141
+ return if block_closer_line?(next_source)
142
142
 
143
143
  add_offense(let_node, message: MSG_MULTILINE_TRAILING)
144
144
  end
145
145
 
146
+ def block_closer_line?(line)
147
+ ['end', '}'].include?(line.strip)
148
+ end
149
+
146
150
  def multiline_let_needs_leading_padding?(previous_line)
147
151
  previous_source = processed_source.lines[previous_line - 1]
148
152
  return false if previous_source.strip.empty?
@@ -153,6 +157,9 @@ class RuboCop::Cop::Munra::LetLayout < RuboCop::Cop::Base
153
157
 
154
158
  def block_opener_line?(line)
155
159
  stripped = line.strip
156
- stripped.end_with?(' do') || stripped == 'do'
160
+ return true if stripped.end_with?('{')
161
+ return true if stripped.match?(/\bdo(\s*\|.*\|)?\s*\z/)
162
+
163
+ false
157
164
  end
158
165
  end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Expectations must use a literal, not a formatter, `I18n.t`, or `t`.
4
+ #
5
+ # Detects forbidden formatters (configurable) and i18n helpers inside
6
+ # `expect(...)` arguments so specs assert concrete values.
7
+ #
8
+ # @example
9
+ # # bad
10
+ # expect(I18n.t('foo.bar')).to eq('bar')
11
+ #
12
+ # # bad
13
+ # expect(t('foo.bar')).to eq('bar')
14
+ #
15
+ # # bad
16
+ # expect(format_cpf(user.cpf)).to eq('123.456.789-00')
17
+ #
18
+ # # good
19
+ # expect(user.cpf).to eq('123.456.789-00')
20
+ #
21
+ # # good
22
+ # expect(page).to have_content('Welcome')
23
+ class RuboCop::Cop::Munra::LiteralExpectation < RuboCop::Cop::Base
24
+ MSG = 'Use literal values in expectations instead of `%<source>s`.'
25
+
26
+ FORBIDDEN_SENDS = {
27
+ t: 'I18n.t / t',
28
+ translate: 'I18n.t / t'
29
+ }.freeze
30
+
31
+ def on_send(node)
32
+ return unless inside_expect_block?(node)
33
+
34
+ offense_for_formatter(node)
35
+ offense_for_i18n(node)
36
+ end
37
+
38
+ private
39
+
40
+ def forbidden_formatters
41
+ cop_config.fetch('ForbiddenFormatters', ['format_cpf', 'format_phone', 'format_cep']).map(&:to_sym)
42
+ end
43
+
44
+ def inside_expect_block?(node)
45
+ node.each_ancestor(:send).any? do |send|
46
+ next false unless send.method_name == :expect && send.receiver.nil?
47
+
48
+ argument = send.first_argument
49
+ next false unless argument
50
+
51
+ node.source_range.overlaps?(argument.source_range)
52
+ end
53
+ end
54
+
55
+ def offense_for_formatter(node)
56
+ return unless forbidden_formatters.include?(node.method_name)
57
+
58
+ add_offense(node, message: format(MSG, source: node.method_name))
59
+ end
60
+
61
+ def offense_for_i18n(node)
62
+ if node.receiver&.const_type? && node.receiver.short_name == :I18n && FORBIDDEN_SENDS.key?(node.method_name)
63
+ add_offense(node, message: format(MSG, source: 'I18n.t'))
64
+ elsif node.receiver.nil? && node.method_name == :t
65
+ add_offense(node, message: format(MSG, source: 't'))
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Enforce model spec sections `associations`, `validations`, and `scopes`
4
+ # in that order, with the expected wrappers and association context names.
5
+ #
6
+ # @example
7
+ # # bad
8
+ # RSpec.describe Foo, type: :model do
9
+ # describe 'scopes' do
10
+ # end
11
+ # end
12
+ #
13
+ # # bad
14
+ # RSpec.describe Foo, type: :model do
15
+ # context 'validations' do
16
+ # end
17
+ #
18
+ # context 'associations' do
19
+ # end
20
+ # end
21
+ #
22
+ # # good
23
+ # RSpec.describe Foo, type: :model do
24
+ # context 'associations' do
25
+ # context 'when belong_to' do
26
+ # end
27
+ # end
28
+ #
29
+ # context 'validations' do
30
+ # end
31
+ #
32
+ # context 'scopes' do
33
+ # describe '.active' do
34
+ # end
35
+ # end
36
+ # end
37
+ class RuboCop::Cop::Munra::ModelSpecStructure < RuboCop::Cop::Base
38
+ include RuboCop::Cop::Munra::ModelScopeNames
39
+ include RuboCop::Cop::Munra::ModelSpecSectionChecks
40
+ include RuboCop::Cop::Munra::RSpecHelpers
41
+
42
+ MSG_ORDER = 'Model specs must list `associations`, `validations`, then `context \'scopes\'` before other sections.'
43
+ MSG_SECTION_CONTEXT = 'Use `context \'%<name>s\'`, not `describe \'%<name>s\'`.'
44
+ MSG_SCOPES_CONTEXT = 'Use `context \'scopes\'`, not `describe \'scopes\'` or `describe \'scope\'`.'
45
+ MSG_MULTIPLE_SCOPES = 'Only one `context \'scopes\'` is allowed.'
46
+ MSG_ASSOCIATION_CONTEXT = 'Association contexts must match `when belong_to`, `when have_many`, `when have_one`, `when have_one_attached`, or `when have_and_belong_to_many`.'
47
+ MSG_SCOPE_AT_ROOT = 'Move `describe \'.%<name>s\'` into `context \'scopes\'`.'
48
+ MSG_NOT_A_SCOPE = '`describe \'.%<name>s\'` inside `context \'scopes\'` must match a model `scope :%<name>s`.'
49
+
50
+ def on_block(node)
51
+ return unless root_example_group?(node)
52
+
53
+ sections = top_level_sections(node)
54
+ check_section_order(sections)
55
+ check_ordered_section_wrappers(sections)
56
+ check_scopes_wrappers(sections)
57
+ check_associations_contexts(sections)
58
+ check_scope_examples(sections)
59
+ end
60
+
61
+ private
62
+
63
+ def ordered_sections
64
+ cop_config.fetch('OrderedSections', ['associations', 'validations', 'scopes'])
65
+ end
66
+
67
+ def ordered_section_context_labels
68
+ ordered_sections - ['scopes']
69
+ end
70
+
71
+ def root_example_group?(node)
72
+ example_group?(node) &&
73
+ node.each_ancestor(:block).none? { |ancestor| ancestor != node && example_group?(ancestor) }
74
+ end
75
+
76
+ def top_level_sections(node)
77
+ block_statement_children(node).select { |child| section_node?(child) }
78
+ end
79
+
80
+ def section_node?(node)
81
+ return false unless node.block_type?
82
+
83
+ send = node.send_node
84
+ return false unless send
85
+
86
+ [:describe, :context].include?(send.method_name)
87
+ end
88
+
89
+ def section_label(node)
90
+ send = node.send_node
91
+ return unless send
92
+ return unless [:describe, :context].include?(send.method_name)
93
+
94
+ name = send.arguments.first&.value&.to_s
95
+ return name if ordered_sections.include?(name)
96
+
97
+ name if send.method_name == :describe
98
+ end
99
+
100
+ def check_ordered_section_wrappers(sections)
101
+ ordered_section_context_labels.each do |label|
102
+ sections.each do |section|
103
+ send = section.send_node
104
+ name = send.arguments.first&.value&.to_s
105
+ next unless name == label
106
+ next if send.method_name == :context
107
+
108
+ add_offense(section, message: format(MSG_SECTION_CONTEXT, name: label))
109
+ end
110
+ end
111
+ end
112
+
113
+ def check_section_order(sections)
114
+ sections_list = ordered_sections
115
+ labels = sections.filter_map { |section| section_label(section) }
116
+ ordered = labels.select { |label| sections_list.include?(label) }
117
+ return if ordered == ordered.sort_by { |label| sections_list.index(label) }
118
+
119
+ add_offense(sections.first, message: MSG_ORDER)
120
+ end
121
+
122
+ def check_scopes_wrappers(sections)
123
+ flag_describe_scope_wrappers(sections)
124
+ flag_duplicate_scopes_contexts(sections)
125
+ end
126
+
127
+ def flag_describe_scope_wrappers(sections)
128
+ sections.each do |section|
129
+ send = section.send_node
130
+ name = send.arguments.first&.value&.to_s
131
+ next unless send.method_name == :describe && ['scope', 'scopes'].include?(name)
132
+
133
+ add_offense(section, message: MSG_SCOPES_CONTEXT)
134
+ end
135
+ end
136
+
137
+ def flag_duplicate_scopes_contexts(sections)
138
+ scopes = sections.select { |section| scopes_context?(section) }
139
+ return if scopes.size <= 1
140
+
141
+ scopes.each { |section| add_offense(section, message: MSG_MULTIPLE_SCOPES) }
142
+ end
143
+
144
+ def scopes_context?(section)
145
+ send = section.send_node
146
+ send.method_name == :context && send.arguments.first&.value == 'scopes'
147
+ end
148
+
149
+ def scope_method_name(node)
150
+ argument = node.send_node.arguments.first
151
+ return unless argument&.str_type?
152
+ return unless argument.value.start_with?('.')
153
+
154
+ argument.value.delete_prefix('.')
155
+ end
156
+ end
@@ -49,7 +49,7 @@ class RuboCop::Cop::Munra::NamedSubjectLayout < RuboCop::Cop::Base
49
49
  MSG_FIRST = '`subject` must be the first declaration in the example group.'
50
50
  MSG_REPEAT = 'Use the named subject `%<name>s` in the expectation instead of repeating its body.'
51
51
 
52
- SUBJECT_METHODS = %i[subject subject!].freeze
52
+ SUBJECT_METHODS = [:subject, :subject!].freeze
53
53
 
54
54
  def on_block(node)
55
55
  check_example_group(node) if example_group?(node)
@@ -59,7 +59,7 @@ class RuboCop::Cop::Munra::NamedSubjectLayout < RuboCop::Cop::Base
59
59
  private
60
60
 
61
61
  def http_methods
62
- Array(cop_config.fetch('HttpMethods', %w[get post put patch delete])).map(&:to_sym)
62
+ Array(cop_config.fetch('HttpMethods', ['get', 'post', 'put', 'patch', 'delete'])).map(&:to_sym)
63
63
  end
64
64
 
65
65
  def check_example_group(node)
@@ -165,15 +165,13 @@ class RuboCop::Cop::Munra::NamedSubjectLayout < RuboCop::Cop::Base
165
165
  def actionable_expression?(node)
166
166
  return false unless node.send_type?
167
167
 
168
- described_class_call?(node) ||
169
- (node.receiver.nil? && http_methods.include?(node.method_name)) ||
170
- (node.method_name == :call && node.receiver&.const_type?)
168
+ described_class_call?(node) || (node.receiver.nil? && http_methods.include?(node.method_name)) || (node.method_name == :call && node.receiver&.const_type?)
171
169
  end
172
170
 
173
171
  def described_class_call?(node)
174
172
  return true if node.method_name == :call && described_class_receiver?(node.receiver)
175
173
 
176
- %i[perform_now perform_later].include?(node.method_name) && described_class_receiver?(node.receiver)
174
+ [:perform_now, :perform_later].include?(node.method_name) && described_class_receiver?(node.receiver)
177
175
  end
178
176
 
179
177
  def described_class_receiver?(receiver)