我有一个特殊的问题,涉及使用data_mapper和sqlite3和rspec节省时间
如果我运行下面的规范,我得到这个失败报告
# expected: 2013-01-04 07:30:00 +1100
# got: 2013-01-04 00:00:00 +1100
如果我尝试在irb中手动保存文件,我会得到
# irb(main):003:0> Sleep.create(:id => 1, :wake_time => Time.new(2013, 01, 04, 07, 30, 00))
# => #<Sleep @id=1 @wake_time=2013-01-04 07:30:00 +1100>
总之,如果我运行rspec测试,它接受一个字符串,将其分解并插入到新的Time对象中,那么Time部分将错误地保存为00:00:00
我还可以确认,在测试运行后,如果我检查db中已测试的记录,时间被错误地保存为00:00:00(以防万一您怀疑rspec的比较或db检索关闭:))
我想弄清这件事的真相——这真的让我很沮丧。特别是考虑到我真的不关心日期(但我想解决这个问题,因为它现在已经激起了我的兴趣;)
另外,如果有更好的方法来实现节省db的时间,我愿意接受建议。谢谢!
life_dm.rb
require "rubygems"
require "json"
require "sqlite3"
require "data_mapper"
require "bigdecimal"
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}../spec/resources/test.db")
class Sleep
include DataMapper::Resource
property :id, Integer, :key => true #easier to get methods when key is id vs week
property :wake_time, Time
end
DataMapper.finalize.auto_migrate!
sleep.rb
def update_sleep_data (id,wake_time)
#I have also tried saving the time as an sql date/time string
#i.e :wake_time => "2013-01-04 #{wake_time[0..1]}:#{wake_time[2..3]}"
#but get the same result with rspec getting
Sleep.create(:id => id, :wake_time => Time.new(2013,01,04,wake_time[0..1].to_i,wake_time[2..3].to_i))
end
sleep_spec.rb
require 'data_mapper'
require_relative '../../data/life_dm'
require_relative '../../methods/sleep'
describe "sleep table" do
it "saves info about sleep to the db" do
@id = 1
@wake_time = "0730"
update_sleep_data(@id, @wake_time)
sleep_1 = Sleep.get 1
sleep_1[:id].should eql 1
sleep_1[:wake_time].should eql Time.new(2013,01,04,07,30,00)
end
end
看起来Time::new
不喜欢你的字符串。而是传递整数,这似乎对其他参数很有效。
在sleep.rb
中使用wake_time[0..1].to_i
和wake_time[2..3].to_i