什么是RSPEC存根?以身作则

时间:2013-09-19 04:21:55

标签: ruby-on-rails ruby rspec stub

我似乎无法掌握究竟是什么存根。

有人可以解释下面的RSPEC代码应该做什么。在这里使用存根有什么好处?

require "performance_monitor"

require "time"  # loads up the Time.parse method -- do NOT create time.rb!

describe "Performance Monitor" do
  before do
    @eleven_am = Time.parse("2011-1-2 11:00:00")
  end

  it "takes exactly 1 second to run a block that sleeps for 1 second (with stubs)" do
    fake_time = @eleven_am
    Time.stub(:now) { fake_time }
    elapsed_time = measure do
      fake_time += 60  # adds one minute to fake_time
    end
    elapsed_time.should == 60
  end

end

我想我能用一个例子来理解。

2 个答案:

答案 0 :(得分:3)

stub用于此override now Time current time的{​​{1}},所以此处不是Time.now之后返回的fake_time存根它将返回{{1}}

答案 1 :(得分:0)

请注意,存根只会在这一个规范中“覆盖”此方法。其他规格将正确回复Time.now