Mysql Rails-使用RSpec设置迁移和测试的默认时间

Mysql Rails-使用RSpec设置迁移和测试的默认时间,mysql,ruby-on-rails,ruby-on-rails-4,rspec,Mysql,Ruby On Rails,Ruby On Rails 4,Rspec,使用Rails 4遗留应用程序&尝试随时间设置一些DB默认值。使用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" en

使用Rails 4遗留应用程序&尝试随时间设置一些DB默认值。使用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
日期部分对我来说没有意义,尽管我不确定当列
type
设置为
time

这可能是由
房间
模型中定义的某些设定器引起的,如下所示:

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)


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

这里的目标是镜像我编写的迁移所创建的默认模式


但是,本规范不符合:

  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

我的问题与此有关:

  • 您应该如何实现此默认设置
  • 如何测试
  • 我甚至应该测试数据库默认值吗
  • 将其添加到工厂感觉就像是在“加载”测试
对于“2000-01-01 12:00:00”的时区是不明确的,但是它为您的日期对象定义得很清楚。通过检查并非100%确定,但与“2000-01-01 12:00:00+0800”相比,您可能会通过测试


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

检查您是否始终使用UTC或时区特定的时区。。。如果你不确定,那么转换期望的两个方面。谢谢Anthony-我从中得出结论,我真的应该放弃这个测试。从测试开销的角度来看,当我可以看到在我的模式中明确定义了缺省值时,这就太过分了。谢谢你提醒我时区。
  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
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