2011-08-26 53 views
12

我想检查一个方法是否被调用完全(n)次,我仍然希望该方法执行其原始功能。考虑一个简单的缩略图系统缓存缩略图文件,并确保ImageMagick的创建缩略图的“转换”可执行文件仅在第一个请求上被调用。rspec 2:检测调用方法,但仍然有它执行其功能

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 

在我的情况下,我逃离了第一次尝试,但可能有情况下,我没有。第二个失败,因为检测到呼叫Thumbnail.convert,但该方法本身不起任何作用。有没有什么办法来检测方法的调用,并让它做到原来的东西?

BTW:我怀疑这是question非常相似,但后来我得到了描述丢失,也很没有答案......

回答

20

现在,有一种方法and_call_original正是因为这个用例。 (RSpec的2.12)

Sinatra::Thumbnails.should_receive(:convert).and_call_original 

的文档可以通过若昂,here引用的同一页面上找到。

参见:changelog

+0

谢谢,像一个魅力工作! – thomax

15

耶!我想我明白了!

it "should detect a cached version" do 
    original_method = Sinatra::Thumbnails.method(:convert) 
    Sinatra::Thumbnails.should_receive(:convert).exactly(1).times do |*args| 
    original_method.call(*args) 
    end 
    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 

它的记录(糟糕,在我看来)在here在最后...

+0

的文件确实是很差,我无法找到你指着页面'original_method'的任何提及。但谢谢你的答案! – lulalala

+0

'original_method'只是我使用的局部变量!我链接到的页面提到“任意处理”,这是我需要调用存储在该局部变量中的方法。 –

+0

我在想什么?对不起,我没有正确阅读:( – lulalala

相关问题