change 匹配器

change 匹配器用于指定一段代码更改了一些可变状态。可以使用两种形式之一来指定更改的内容

可以通过链接from 和/或to 或者byby_at_mostby_at_least 之一来进一步限定更改。

背景

假设 一个名为“lib/counter.rb”的文件,内容如下

class Counter
  class << self
    def increment
      @count ||= 0
      @count += 1
    end

    def count
      @count ||= 0
    end
  end
end

期望更改

假设 一个名为“spec/example_spec.rb”的文件,内容如下

require "counter"

RSpec.describe Counter, "#increment" do
  it "should increment the count" do
    expect { Counter.increment }.to change { Counter.count }.from(0).to(1)
  end

  # deliberate failure
  it "should increment the count by 2" do
    expect { Counter.increment }.to change { Counter.count }.by(2)
  end
end

我运行 rspec spec/example_spec.rb

那么 输出应包含“1 个失败”

那么 输出应包含“预期Counter.count 更改了 2,但实际更改了 1”。

期望无更改

假设 一个名为“spec/example_spec.rb”的文件,内容如下

require "counter"

RSpec.describe Counter, "#increment" do
  it "should not increment the count by 1 (using not_to)" do
    expect { Counter.increment }.not_to change { Counter.count }
  end

  it "should not increment the count by 1 (using to_not)" do
    expect { Counter.increment }.to_not change { Counter.count }
  end
end

我运行 rspec spec/example_spec.rb

那么 输出应包含“2 个失败”

那么 输出应包含“预期Counter.count 未更改,但实际从 1 更改为 2”。