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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
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)`.'
MSG_CALL =
'Prefer `change { %<obj>s.%<attr>s }`.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Instance Method Details

#on_block(node) ⇒ Object


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

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

  expect_change_with_block(node) do |receiver, message|
    msg = format(MSG_BLOCK, obj: receiver, attr: message)
    add_offense(node, message: msg) do |corrector|
      replacement = "change(#{receiver}, :#{message})"
      corrector.replace(node, replacement)
    end
  end
end

#on_send(node) ⇒ Object


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

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

  expect_change_with_arguments(node) do |receiver, message|
    msg = format(MSG_CALL, obj: receiver, attr: message)
    add_offense(node, message: msg) do |corrector|
      replacement = "change { #{receiver}.#{message} }"
      corrector.replace(node, replacement)
    end
  end
end