如何解决纳秒级的Rails TimeHelpers travel_to无法正常工作
在我的代码中,我有Time.current.strftime('%Y%m%d%H%M%S%6N')
并测试我是否使用了Rails TimeHelpers #travel_to方法。
在测试中:
travel_to Time.local(2015,2,11,14,30.123456) do
...
end
问题是Time.current.strftime('%Y%m%d%H%M%S%6N')
在应为123456的情况下返回000000纳秒。
附近有工作吗?我现在暂时不使用TimeCop gem。
解决方法
不幸的是,Rails的travel_to
将值截断为秒。从文档中:
请注意,将所用时间的usec设置为0,以防止外部服务(例如MySQL)舍入错误(它将舍入而不是舍入,导致出现一秒钟的错误)。
作为解决方法,您可以更改代码以接受明确的时间,并将当前时间作为默认时间:
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,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,14)) { example.run }
end
it 'generates the current timestamp' do
expect(your_method).to eq('20150202111400000000')
end
end
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。