仅在第一次使用 Rspec 调用时存根方法 [英] stub method only on the first call with Rspec

查看:58
本文介绍了仅在第一次使用 Rspec 调用时存根方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在第一次调用时存根方法,而在第二次调用时它的行为应符合预期?

How can I stub a method only on the first call, and in the second one it should behave as expected?

我有以下方法:

def method
  do_stuff
rescue => MyException
  sleep rand
  retry
end

我想在第一次调用 do_stuff 时引发 MyException,但在第二次调用中,行为正常.我需要实现这一点来测试我的 rescue 块,而不会出现无限循环.

I want to the first call of do_stuff to raise MyException, but in the second call, behaves normally. I need to achieve this to test my rescue block without getting an infinite loop.

有没有办法做到这一点?

Is there a way to achieve this?

推荐答案

您可以将块传递给存根,该存根将在调用存根时被调用.然后,除了执行您需要的任何操作外,您还可以在其中执行取消存根.

You can pass a block to a stub that will be invoked when the stub is called. You can then perform the unstub in there, in addition to doing whatever you need to.

class Foo
  def initialize
    @calls = 0
  end

  def be_persistent
    begin
      increment
    rescue
      retry
    end
  end

  def increment
    @calls += 1
  end
end

describe "Stub once" do
  let(:f) { Foo.new }
  before {
    f.stub(:increment) { f.unstub(:increment); raise "boom" }
  }

  it "should only stub once" do
    f.be_persistent.should == 1
  end
end

似乎在这里工作得很好.

Seems to work nicely here.

$ rspec stub.rb -f doc

Stub once
  should only stub once

Finished in 0.00058 seconds
1 example, 0 failures

或者,您可以只跟踪调用次数并根据调用次数为存根返回不同的结果:

Alternately, you could just track the number of calls and return different results for the stub based on the call count:

describe "Stub once" do
  let(:f) { Foo.new }

  it "should return different things when re-called" do
    call_count = 0
    f.should_receive(:increment).twice {
      if (call_count += 1) == 1
        raise "boom"
      else
        "success!"
      end
    }

    f.be_persistent.should == "success!"
  end
end

这篇关于仅在第一次使用 Rspec 调用时存根方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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