ruby 使用RSpec存根Time.now

7qhs6swi  于 2023-03-17  发布在  Ruby
关注(0)|答案(4)|浏览(181)

我尝试Time.now在RSpec中存根www.example.com,如下所示:

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

知道为什么会这样吗?

5m1hhzi4

5m1hhzi41#

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

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

参见RSpec Mocks 3.3

hwamh0ep

hwamh0ep2#

ActiveSupporttravel_to的转换就很成功:

RSpec.describe Something do
  it 'fixes time' do
    travel_to Time.zone.parse('1970-01-01')
    verify
    travel_back
  end
end
gupuwyp2

gupuwyp23#

可以使用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)和测试中

nwwlzxa7

nwwlzxa74#

您始终可以使用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

相关问题