【问题标题】:Rails - Setting default time in migration and testing with RSpecRails - 使用 RSpec 设置迁移和测试的默认时间
【发布时间】:2016-04-11 06:16:59
【问题描述】:

使用 Rails 4 旧版应用程序并尝试使用 Time 设置一些数据库默认值。使用 MySQL。我添加了一个迁移:

class AddDefaultsToCheckInAndCheckOut < ActiveRecord::Migration
  def change
    change_column_default :rooms, :check_in_time, "12:00"
    change_column_default :rooms, :check_out_time, "09:00"
  end
end

架构现在显示:

t.time "check_in_time", default: "2000-01-01 12:00:00"
t.time "check_out_time", default: "2000-01-01 09:00:00"

日期部分对我来说没有意义,虽然我不确定为什么当列 type 设置为 time 时需要它

这可能是由Room 模型中定义的一些设置器引起的,如下所示:

def check_in_hours=(hours)
  begin
    self.check_in_time = hours.present? ? Time.utc(2001,1,1, hours, self.check_in_time.try(:min)) : nil
  rescue ArgumentError
  end
end

def check_in_mins=(minutes)
  begin
    if self.check_in_time.try(:hour)
      self.check_in_time =  Time.utc(2001, 1, 1, self.check_in_time.try(:hour), (minutes.present? ? minutes : 0))
    else
      self.check_in_time =  nil
    end
  rescue ArgumentError
  end
end

我添加了一些规范来检查我的工作 (room_spec.rb)

  it "defaults to 12:00 check in time if not specified" do
    expect(room.check_in_time).to eq "2000-01-01 12:00:00"
  end

然后也添加到工厂(factories/rooms.rb)

check_in_time "2000-01-01 12:00:00"
check_out_time "2000-01-01 09:00:00"

这里的目的是镜像我编写的迁移创建的架构默认值。


但是这个规范失败了:

  1) Room defaults to 12:00 check in time if not specified
     Failure/Error: expect(room.check_in_time).to eq "2000-01-01 12:00:00"
        expected: "2000-01-01 12:00:00"
        got: 2000-01-01 12:00:00.000000000 +0800

我的问题是:

  • 应该如何实现这个默认值?
  • 以及如何测试?
  • 我是否应该测试数据库默认值?
  • 将其添加到 Factory 感觉就像是在“加载”测试。

【问题讨论】:

  • 检查您是否始终使用 UTC 或特定时区的时区...如果您不确定,请转换预期的两边。

标签: mysql ruby-on-rails ruby-on-rails-4 rspec


【解决方案1】:

“2000-01-01 12:00:00”的时区不明确,但已为您的日期对象明确定义。通过检查不是 100% 确定,但与“2000-01-01 12:00:00 +0800”相比,您可能会通过测试。

也就是说,这不是一个非常有用的测试,尤其是在这种粒度级别上,因为它微不足道,以至于您的测试比负责其行为的实际代码更复杂。但是,如果这个值非常重要并且您想保持测试,我建议降低比较的时间分辨率,只比较小时和分钟,或者可能只比较小时,以免您必须维护浮点错误等。

【讨论】:

  • 谢谢 Anthony - 我认为我真的应该放弃对此的测试。当我看到在我的模式中明确定义了默认值时,从测试开销的角度来看,这是矫枉过正的。感谢 TimeZone 的提醒。
猜你喜欢
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
相关资源
最近更新 更多