Class: RuboCop::Cop::RSpec::ExpectChange

Inherits:
Cop
  • Object
show all
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rspec/expect_change.rb

Overview

Checks for consistent style of change matcher.

Enforces either passing object and attribute as arguments to the matcher or passing a block that reads the attribute value.

This cop can be configured using the ‘EnforcedStyle` option.

Examples:

‘EnforcedStyle: block`

# bad
expect(run).to change(Foo, :bar)

# good
expect(run).to change { Foo.bar }

‘EnforcedStyle: method_call`

# bad
expect(run).to change { Foo.bar }
expect(run).to change { foo.baz }

# good
expect(run).to change(Foo, :bar)
expect(run).to change(foo, :baz)
# also good when there are arguments or chained method calls
expect(run).to change { Foo.bar(:count) }
expect(run).to change { user.reload.name }

Constant Summary collapse

MSG_BLOCK =
'Prefer `change(%<obj>s, :%<attr>s)`.'.freeze
MSG_CALL =
'Prefer `change { %<obj>s.%<attr>s }`.'.freeze

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/rubocop/cop/rspec/expect_change.rb', line 72

def autocorrect(node)
  if style == :block
    autocorrect_method_call_to_block(node)
  else
    autocorrect_block_to_method_call(node)
  end
end

#on_block(node) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/rubocop/cop/rspec/expect_change.rb', line 61

def on_block(node)
  return unless style == :method_call

  expect_change_with_block(node) do |receiver, message|
    add_offense(
      node,
      message: format(MSG_BLOCK, obj: receiver, attr: message)
    )
  end
end

#on_send(node) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/rspec/expect_change.rb', line 50

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

  expect_change_with_arguments(node) do |receiver, message|
    add_offense(
      node,
      message: format(MSG_CALL, obj: receiver, attr: message)
    )
  end
end