【发布时间】:2012-08-22 23:27:21
【问题描述】:
在编写 Rspec 测试时,我经常对 should_receive 感到沮丧。我想知道是否有不那么侵入性的替代方案。
例如:
describe "making a cake" do
it "should use some other methods" do
@baker.should_receive(:make_batter)
@baker.make_cake
end
end
对should_receive 的调用是一个很好的描述,但它破坏了我的代码,因为should_receive 通过屏蔽原始方法起作用,并且make_cake 无法继续,除非make_batter 实际上返回一些击球手。所以我把它改成这样:
@baker.should_receive(:make_batter).and_return(@batter)
这很丑,因为:
- 它看起来好像我正在测试
make_batter正确返回@batter,但我实际上强制make_batter的假版本返回它. - 强制我单独设置
@batter - 如果
make_batter有任何重要的副作用(我想可能是代码异味),我也必须让这些发生。
我希望should_receive(:make_batter) 能够验证方法调用并将其传递给原始方法。如果我想对它的行为进行存根以进行更好的隔离测试,我会明确地这样做:@baker.stub(:make_batter).and_return(@batter)。
有没有办法在不阻止原始方法调用的情况下执行should_receive 之类的操作?我的问题是糟糕设计的征兆吗?
【问题讨论】: