Rails TimeHelpers travel_to 纳秒不工作

Rails TimeHelpers travel_to with nanosecond not working

在我的代码中有 Time.current.strftime('%Y%m%d%H%M%S%6N') 并测试我是否使用了 Rails TimeHelpers #travel_to 方法。

在测试中:

travel_to Time.local(2015, 2, 2, 11, 14, 30.123456) do
  ...
end

问题是 Time.current.strftime('%Y%m%d%H%M%S%6N') returns 000000 纳秒,而它应该是 123456。

有解决办法吗?我现在尽量不使用 TimeCop gem。

不幸的是,Rails' travel_to 将值截断为秒。来自文档:

Note that the usec for the time passed will be set to 0 to prevent rounding errors with external services, like MySQL (which will round instead of floor, leading to off-by-one-second errors).

作为解决方法,您可以更改代码以接受将当前时间作为默认时间的显式时间:

def your_method(time = Time.current)
  time.strftime('%Y%m%d%H%M%S%6N')
end

在你的测试中:

describe '#your_method' do
  context 'with an explicit time value' do
    let(:time) { Time.local(2015, 2, 2, 11, 14, 30.123456) }

    it 'generates the corresponding timestamp' do
      expect(your_method(time)).to eq('20150202111430123456')
    end
  end

  context 'without argument' do
    around do |example|
      travel_to(Time.local(2015, 2, 2, 11, 14)) { example.run }
    end

    it 'generates the current timestamp' do
      expect(your_method).to eq('20150202111400000000')
    end
  end
end