rubytestingrspecrspec-expectations

How to execute once and expect multiple changes with RSpec?


If I want to test, that an operation produces certain side-effects, how can I execute the operation once and use the change rspec matcher. Example:

expect { some_method }.to change(Foo, :count).by(1)
expect { some_method }.to change(Bar, :count).by(1)
expect { some_method }.to change(Baz, :count).by(1)

How can I execute some_method only once, instead of 3 times?

Or do I need to do something like:

foo_count_before = Foo.count
bar_count_before = Bar.count
baz_count_before = Baz.count

some_method

foo_count_after= Foo.count
bar_count_after= Bar.count
baz_count_after= Baz.count

expect(foo_count_after - foo_count_before).to eq 1
expect(bar_count_after - bar_count_before).to eq 1
expect(baz_count_after - baz_count_before).to eq 1

Solution

  • You can join multiple expectations together using compound expectations. In your example, this can look like this:

    expect { some_method }
      .to change(Foo, :count).by(1)
      .and change(Bar, :count).by(1)
      .and change(Baz, :count).by(1)