gpt4 book ai didi

ruby-on-rails - Rails TimeHelpers travel_to with nanosecond 不工作

转载 作者:行者123 更新时间:2023-12-04 08:36:15 25 4
gpt4 key购买 nike

在我的代码中我有 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') 返回 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

关于ruby-on-rails - Rails TimeHelpers travel_to with nanosecond 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64785350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com