【发布时间】: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