Rails 时间格式测试失败,因为它有一个小时?



我在我的一个Rails类中有以下方法:

def human_departure_time
  "#{departure_time.strftime("%A, %d %B %Y")} at #{departure_time.strftime("%I:%M %p")}"
end

正如您所看到的,它只是获取模型的datetime属性并对其进行格式化,使其更人性化。

无论如何,我对这个方法进行了以下测试:

describe "human_departure_time" do
  it "should output the time in readable format" do
    # first I use the Timecop gem to freeze the time
    Timecop.freeze(DateTime.now) do
      bus_time = DateTime.now + 1.days
      # factory a bus with a specific departure time
      bus = Factory :bus, departure_time: bus_time
      expected = "#{bus_time.strftime("%A, %d %B %Y")} at #{bus_time.strftime("%I:%M %p")}"
      # check that the output is as expected
      bus.human_departure_time.should == expected
    end
  end
end

非常简单,但是测试失败一个小时,输出如下:

Failures:
  1) Bus human_departure_time should output the time in readable format
     Failure/Error: bus.human_departure_time.should == expected
       expected: "Wednesday, 17 August 2011 at 03:13 AM"
            got: "Wednesday, 17 August 2011 at 02:13 AM" (using ==)
     # ./spec/models/bus_spec.rb:34:in `block (4 levels) in <top (required)>'
     # ./spec/models/bus_spec.rb:30:in `block (3 levels) in <top (required)>'
这是我的公共汽车工厂,以防万一。在我的测试中,我用冻结时间加上一个小时来覆盖出发时间。
factory :bus do
  origin_name "Drogheda"
  event_name "EP"
  departure_time { DateTime.now + 14.days }
end

我猜这与夏令时或其他什么有关?我如何解决这个问题?

ActiveRecord可以自动将模型中的时间属性转换为本地时间。

您可以尝试使用strftime%Z参数来查看输出时间戳的时区,以查看可能的转换潜入您的时间。

一些可能相关的谷歌提示:


default_timezone:

http://apidock.com/rails/ActiveRecord/Base/default_timezone/class


ActiveRecord::Base.time_zone_aware_attributes
config.active_record.time_zone_aware_attributes:

http://tamersalama.com/2011/01/10/rails-disable-timezone-conversions/
https://mirrors.kilnhg.com/Repo/Mirrors/From-Git/Rails/History/70cb470c1ab8
http://www.ruby-forum.com/topic/2096919
http://www.ruby-forum.com/topic/890711


相关内容

  • 没有找到相关文章