Stpecbing Time.now与RSpec

时间:2015-08-30 19:42:44

标签: ruby rspec

我试图在RSpec中将Time.now存根如下:

it "should set the date to the current date" do
    @time_now = Time.now
    Time.stub!(:now).and_return(@time_now)

    @thing.capture_item("description")
    expect(@thing.items[0].date_captured).to eq(@time_now)
end

执行此操作时出现以下错误:

 Failure/Error: Time.stub!(:now).and_return(@time_now)
 NoMethodError:
   undefined method `stub!' for Time:Class

知道为什么会这样吗?

4 个答案:

答案 0 :(得分:38)

根据您的RSpec版本,您可能希望使用较新的语法:

allow(Time).to receive(:now).and_return(@time_now)

请参阅RSpec Mocks 3.3

答案 1 :(得分:2)

您始终可以使用timecop

@time_now = Time.now

Timecop.freeze(@time_now) do
  @thing.capture_item("description")
  expect(@thing.items[0].date_captured).to eq(@time_now)
end

答案 2 :(得分:1)

ActiveSupport中的

travel_to可能会更好地达到目的,并且可能如下所示:

def test_date
  travel_to Time.zone.parse('1970-01-01')
  verify
  travel_back
end

答案 3 :(得分:1)

您可以使用timecop。冻结测试之前的时间,然后冻结之后的时间。

describe "some tests" do
  before do
    Timecop.freeze(Time.now)
  end

  after do
    Timecop.return
  end

  it "should do something" do
  end
end

或使用

定义特定时间
let(:time_now) { Time.now }

并在Timecop.freeze(time_now)和测试中使用