如果我想测试一个操作会产生某些副作用,我该如何执行一次操作并使用change
rspec匹配器。例如:
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)
如何只执行some_method
一次,而不是3次?
或者我需要做类似的事情:
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
答案 0 :(得分:4)
您可以使用compound expectations一起加入多个期望。在您的示例中,这可能如下所示:
expect { some_method }
.to change(Foo, :count).by(1)
.and change(Bar, :count).by(1)
.and change(Baz, :count).by(1)