当仅使用rspec时,sqlite3 / data_mapper始终将时间保存为00:00:00

时间:2013-01-09 07:43:42

标签: ruby datetime sqlite rspec2 sqlite3-ruby

我有一个特殊的问题,包括使用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

我还可以确认,在测试运行后,如果我检查数据库中已经测试的记录,则时间被错误地保存为00:00:00(以防万一你怀疑与rspec的comaprison有关或数据库检索关闭:))

我很想深究这一点 - 这真让我感到沮丧。特别是考虑到我并不真正关心约会(但我想解决这个问题,因为它现在激起了我的兴趣;)

此外,如果有更好的方法来实现为数据库节省时间,我愿意接受建议。谢谢!

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

1 个答案:

答案 0 :(得分:0)

看起来Time::new不喜欢你的字符串。相反,传入整数,这似乎适用于其他参数。

sleep.rb中使用wake_time[0..1].to_iwake_time[2..3].to_i