Class: RuboCop::Cop::RSpec::FactoryBot::CreateList

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rspec/factory_bot/create_list.rb

Overview

Checks for create_list usage.

This cop can be configured using the ‘EnforcedStyle` option

Examples:

‘EnforcedStyle: create_list`

# bad
3.times { create :user }

# good
create_list :user, 3

# good
3.times { |n| create :user, created_at: n.months.ago }

‘EnforcedStyle: n_times`

# bad
create_list :user, 3

# good
3.times { create :user }

Defined Under Namespace

Modules: Corrector Classes: CreateListCorrector, TimesCorrector

Constant Summary collapse

MSG_CREATE_LIST =
'Prefer create_list.'
MSG_N_TIMES =
'Prefer %<number>s.times.'
RESTRICT_ON_SEND =
%i[create_list].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#factory_call(node) ⇒ Object



45
46
47
# File 'lib/rubocop/cop/rspec/factory_bot/create_list.rb', line 45

def_node_matcher :factory_call, <<-PATTERN
  (send ${(const nil? {:FactoryGirl :FactoryBot}) nil?} :create (sym $_) $...)
PATTERN

#factory_list_call(node) ⇒ Object



50
51
52
# File 'lib/rubocop/cop/rspec/factory_bot/create_list.rb', line 50

def_node_matcher :factory_list_call, <<-PATTERN
  (send {(const nil? {:FactoryGirl :FactoryBot}) nil?} :create_list (sym _) (int $_) ...)
PATTERN

#n_times_block_without_arg?(node) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/rubocop/cop/rspec/factory_bot/create_list.rb', line 36

def_node_matcher :n_times_block_without_arg?, <<-PATTERN
  (block
    (send (int _) :times)
    (args)
    ...
  )
PATTERN

#on_block(node) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/rspec/factory_bot/create_list.rb', line 54

def on_block(node)
  return unless style == :create_list
  return unless n_times_block_without_arg?(node)
  return unless contains_only_factory?(node.body)

  add_offense(node.send_node, message: MSG_CREATE_LIST) do |corrector|
    CreateListCorrector.new(node.send_node).call(corrector)
  end
end

#on_send(node) ⇒ Object



64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/rspec/factory_bot/create_list.rb', line 64

def on_send(node)
  return unless style == :n_times

  factory_list_call(node) do |count|
    message = format(MSG_N_TIMES, number: count)
    add_offense(node.loc.selector, message: message) do |corrector|
      TimesCorrector.new(node).call(corrector)
    end
  end
end