rspec 2:检测对方法的调用但仍然执行其功能

Joa*_*ora 12 rspec2

我想检查一个方法是否被完全(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检测到了调用,但方法本身没有做任何事情.有没有办法只检测对方法的调用并让它做原始的事情?

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

kpa*_*615 20

现在有一种and_call_original方法正是针对这个用例.(RSpec 2.12)

Sinatra::Thumbnails.should_receive(:convert).and_call_original
Run Code Online (Sandbox Code Playgroud)

该文件可以通过引用若奥在同一个页面上找到,这里.

另请参见:changelog


Joa*_*ora 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
Run Code Online (Sandbox Code Playgroud)

在最后这里记录(在我看来很差)...