在编写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
Run Code Online (Sandbox Code Playgroud)
调用should_receive是一个很好的描述,但它会破坏我的代码,因为should_receive通过屏蔽原始方法来工作,并且make_cake除非make_batter实际返回一些电池,否则无法继续.所以我改成它:
@baker.should_receive(:make_batter).and_return(@batter)
Run Code Online (Sandbox Code Playgroud)
这很难看,因为:
make_batter正确返回@batter,但我居然强迫的仿版make_batter,以返回.@battermake_batter有任何重要的副作用(这可能是代码味道,我想)我也必须让这些发生.我希望这should_receive(:make_batter)将验证方法调用并将其传递给原始方法.如果我想将其行为存根以进行更好的隔离测试,我会明确地这样做:@baker.stub(:make_batter).and_return(@batter).
有没有办法做一些像should_receive没有阻止原始方法调用?我的问题是设计糟糕的症状吗?
我想检查一个方法是否被完全(n)次调用,但我仍然希望该方法执行其原始函数.考虑一个简单的缩略图系统来缓存缩略图文件,并确保只在第一个请求时调用创建缩略图的ImageMagick的"转换"可执行文件.
it "this passes: should detect a cached version" do
thumbnail_url = thumbnail_url_for("images/something.jpg")
get thumbnail_url
last_response.should be_ok
Sinatra::Thumbnail.should_not_receive(:convert)
get thumbnail_url
last_response.should be_ok
end
it "this fails: should detect a cached version" do
Sinatra::Thumbnail.should_receive(:convert).exactly(1).times
thumbnail_url = thumbnail_url_for("images/something.jpg")
get thumbnail_url
last_response.should be_ok
get thumbnail_url
last_response.should be_ok
end
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我第一次尝试逃脱,但可能有一些我不这样做的情况.第二个失败是因为Thumbnail.convert检测到了调用,但方法本身没有做任何事情.有没有办法只检测对方法的调用并让它做原始的事情?
顺便说一句:我怀疑这个问题非常相似,但后来我在描述中迷失了,也没有答案......