我有一个has_many曲目的播放列表。每个轨道的持续时间为整数(以毫秒为单位)。 我想要计算播放列表的总持续时间。实际上我从我的播放列表模型中做了类似的事情:
def total_tracks_duration
seconds = tracks.sum(:duration) / 1000
Time.at(seconds).strftime("%H:%M:%S")
end
播放列表规范:
it '#total_tracks_duration' do
play = build(:playlist)
3.times do
create(:track, playlist: play, duration: 60000)
end
expect(play.total_tracks_duration).to eq("00:03:00")
end
最后我遇到了这个失败:
Failures:
1) Playlist #total_tracks_duration
Failure/Error: expect(play.total_tracks_duration).to eq("00:03:00")
expected: "00:03:00"
got: "01:00:00"
(compared using ==)
# ./spec/models/playlist_spec.rb:51:in `block (2 levels) in <top (required)>'
Finished in 0.69605 seconds (files took 9.83 seconds to load)
1 example, 1 failure
我犯错误的地方?
答案 0 :(得分:2)
它为你的时区添加一个偏移量(UTC + 1),所以只需要
Time.at(seconds).utc.strftime("%H:%M:%S")
它应该工作:)