Skip to content

Change example

Cyril Kato edited this page Nov 1, 2026 · 1 revision

change(object, :method) observes the value of object.method across the block. to requires a change to that value; by, by_at_least and by_at_most a numeric difference; from … to the two values. The object to observe must exist when the matcher is built: here, a helper memoized by hand.

require "r_spec"

RSpec.describe "a change" do
  let(:list) { @list ||= [] }
  let(:text) { @text ||= +"foo" }

  it { expect { list << 1 }.to change(list, :length).by(1) }
  it { expect { list << 1 }.to change(list, :length).by_at_least(1) }
  it { expect { list << 1 }.to change(list, :length).by_at_most(1) }
  it { expect { text.upcase! }.to change(text, :to_s).from("foo").to("FOO") }
  it { expect { text.upcase! }.to change(text, :to_s).to("FOO") }
  it { expect { text.upcase }.not_to change(text, :to_s).to("FOO") }
end
$ ruby spec/change_spec.rb
spec/change_spec.rb:7: Success: expected [1] to change by 1
spec/change_spec.rb:8: Success: expected [1] to change by at least 1
spec/change_spec.rb:9: Success: expected [1] to change by at most 1
spec/change_spec.rb:10: Success: expected "FOO" to change from "foo" to "FOO"
spec/change_spec.rb:11: Success: expected "FOO" to change to "FOO"
spec/change_spec.rb:12: Success: expected "FOO" not to change to "FOO"

Clone this wiki locally