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

标签 ruby-on-rails ruby rspec ruby-on-rails-5 rspec-rails

在我的代码中我有 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/

相关文章:

ruby-on-rails - 创建自定义 rspec 变量,如 Controller 规范的响应

ruby-on-rails - has_one_attached 时的默认附件

ruby-on-rails - Ruby 不断给出未知的错误信息

mysql - 安装用于 Ruby 的 MySQL gem 以及 JRuby gem

ruby-on-rails - RSPEc - #<RoomsController :0x0000010534c050> 的未定义方法 `stubs'

ruby-on-rails - Rails + jQuery ajaxPrefilter

ruby-on-rails - 通过哈希值查找哈希数组的交集

ruby - 运行最后一行后让 byebug 留在作用域/函数中

testing - 这个 rspec 辅助测试我做错了什么?

ruby-on-rails - rspec 升级到 3.1.0 后,与 allowed_any_instance_of 一起使用的 and_call_original 不起作用