rspec 2:检测对方法的调用,但仍让它执行其功能 [英] rspec 2: detect call to method but still have it perform its function

查看:45
本文介绍了rspec 2:检测对方法的调用,但仍让它执行其功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个方法是否被精确调用了 (n) 次,但是我仍然希望该方法执行其原始功能.考虑一个简单的缩略图系统,它缓存缩略图文件并确保仅在第一次请求时调用 ImageMagick 的转换"可执行文件来创建缩略图.

I want to check if a method was called exactly(n) times, but I still want that method to perform its original function. Consider a simple thumbnailing system that caches the thumbnail file and make sure ImageMagick's "convert" executable that creates the thumbnail is only called on the first request.

  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 但该方法本身没有做任何事情.有什么方法可以检测对方法的调用并让它做它的原始事情吗?

In my case I get away with my first attempt, but there could be cases where I don't. The second one fails because the call Thumbnail.convert is detected but the method itself doesn't do anything. Is there some way to just detect the call to the method and have it do it's original thing?

顺便说一句:我怀疑这个问题 非常相似,但后来我在描述中迷失了方向,而且也没有答案...

BTW: I suspect this question is very similar, but then I get lost in the description and also it's unanswered...

推荐答案

现在有一个 and_call_original 方法正好适用于这个用例.(RSpec 2.12)

Now there's an and_call_original method precisely for this use case. (RSpec 2.12)

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

该文档可以在 Joao 引用的同一页面上找到,此处.

The documentation can be found on the same page referenced by Joao, here.

另见:变更日志

这篇关于rspec 2:检测对方法的调用,但仍让它执行其功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆