如何使用 RSpec 执行一次并期待多次更改?
How to execute once and expect multiple changes with RSpec?
如果我想测试某个操作会产生某些副作用,我如何执行该操作一次并使用 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
您可以使用 compound expectations 将多个期望连接在一起。在您的示例中,这可能如下所示:
expect { some_method }
.to change(Foo, :count).by(1)
.and change(Bar, :count).by(1)
.and change(Baz, :count).by(1)
如果我想测试某个操作会产生某些副作用,我如何执行该操作一次并使用 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
您可以使用 compound expectations 将多个期望连接在一起。在您的示例中,这可能如下所示:
expect { some_method }
.to change(Foo, :count).by(1)
.and change(Bar, :count).by(1)
.and change(Baz, :count).by(1)