Class: RuboCop::Cop::RSpec::BeforeAfterAll

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/before_after_all.rb

Overview

Check that before/after(:all/:context) isn’t being used.

Examples:

# bad - Faster but risk of state leaking between examples
describe MyClass do
  before(:all) { Widget.create }
  after(:context) { Widget.delete_all }
end

# good - Slower but examples are properly isolated
describe MyClass do
  before(:each) { Widget.create }
  after(:each) { Widget.delete_all }
end

Constant Summary collapse

MSG =
'Beware of using `%<hook>s` as it may cause state to leak ' \
'between tests. If you are using `rspec-rails`, and ' \
'`use_transactional_fixtures` is enabled, then records created ' \
'in `%<hook>s` are not automatically rolled back.'
RESTRICT_ON_SEND =
Set[:before, :after].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

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

Instance Method Details

#before_or_after_all(node) ⇒ Object



30
31
32
# File 'lib/rubocop/cop/rspec/before_after_all.rb', line 30

def_node_matcher :before_or_after_all, <<~PATTERN
  $(send _ RESTRICT_ON_SEND (sym {:all :context}))
PATTERN

#on_send(node) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/rspec/before_after_all.rb', line 34

def on_send(node)
  before_or_after_all(node) do |hook|
    add_offense(
      node,
      message: format(MSG, hook: hook.source)
    )
  end
end