Method: RSpec::Matchers#change

Defined in:
lib/rspec/matchers.rb

#change(receiver = nil, message = nil, &block) ⇒ Object Also known as: a_block_changing, changing

Applied to a proc, specifies that its execution will cause some value to change.

You can either pass receiver and message, or a block, but not both.

When passing a block, it must use the { ... } format, not do/end, as { ... } binds to the change method, whereas do/end would errantly bind to the expect(..).to or expect(...).not_to method.

You can chain any of the following off of the end to specify details about the change:

  • from
  • to

or any one of:

  • by
  • by_at_least
  • by_at_most

== Notes

Evaluates receiver.message or block before and after it evaluates the block passed to expect. If the value is the same object, its before/after hash value is used to see if it has changed. Therefore, your object needs to properly implement hash to work correctly with this matcher.

expect( ... ).not_to change supports the form that specifies from (which specifies what you expect the starting, unchanged value to be) but does not support forms with subsequent calls to by, by_at_least, by_at_most or to.

Examples:

expect {
  team.add_player(player)
}.to change(roster, :count)

expect {
  team.add_player(player)
}.to change(roster, :count).by(1)

expect {
  team.add_player(player)
}.to change(roster, :count).by_at_least(1)

expect {
  team.add_player(player)
}.to change(roster, :count).by_at_most(1)

string = "string"
expect {
  string.reverse!
}.to change { string }.from("string").to("gnirts")

string = "string"
expect {
  string
}.not_to change { string }.from("string")

expect {
  person.happy_birthday
}.to change(person, :birthday).from(32).to(33)

expect {
  employee.develop_great_new_social_networking_app
}.to change(employee, :title).from("Mail Clerk").to("CEO")

expect {
  doctor.leave_office
}.to change(doctor, :sign).from(/is in/).to(/is out/)

user = User.new(:type => "admin")
expect {
  user.symbolize_type
}.to change(user, :type).from(String).to(Symbol)

Parameters:

  • receiver (Object) (defaults to: nil)
  • message (Symbol) (defaults to: nil)

    the message to send the receiver



492
493
494
# File 'lib/rspec/matchers.rb', line 492

def change(receiver=nil, message=nil, &block)
  BuiltIn::Change.new(receiver, message, &block)
end