class RuboCop::Cop::RSpec::ExpectChange
expect { run }.to change { Foo.bar }
# good
expect { run }.to change(Foo, :bar)
# bad
@example ‘EnforcedStyle: block`
expect { run }.to change { user.reload.name }
expect { run }.to change { Foo.bar(:count) }
# also good when there are arguments or chained method calls
expect { run }.to change(foo, :baz)
expect { run }.to change(Foo, :bar)
# good
expect { run }.to change { foo.baz }
expect { run }.to change { Foo.bar }
# bad
@example `EnforcedStyle: method_call` (default)
—-
# `my_method` is called once, but `message` is called on it twice
expect { run }.to change(my_method, :message)
# `my_method` is called before and after `run`
expect { run }.to change { my_method.message }
changing from `block` to `method_call` style may break your test.
you expect it to be called before and after the `expect` block,
If your receiver is dynamic (e.g., the result of a method call) and
expression twice, including the receiver.
calling the `expect` block, whereas `block` style calls the
receiver once and sends the message to it before and after
Autocorrection is unsafe because `method_call` style calls the
@safety
This cop can be configured using the `EnforcedStyle` option.
or a block.
Enforces either passing a receiver and message as method arguments,
Checks for consistent style of change matcher.
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler return unless style == :method_call expect_change_with_block(node) do |receiver, message| msg = format(MSG_BLOCK, obj: receiver.source, attr: message) add_offense(node, message: msg) do |corrector| replacement = "change(#{receiver.source}, :#{message})" corrector.replace(node, replacement) end end end
def on_send(node)
def on_send(node) return unless style == :block expect_change_with_arguments(node) do |receiver, message| msg = format(MSG_CALL, obj: receiver.source, attr: message) add_offense(node, message: msg) do |corrector| replacement = "change { #{receiver.source}.#{message} }" corrector.replace(node, replacement) end end end