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

时间:2011-08-16 02:27:56

标签: ruby-on-rails ruby ruby-on-rails-3 datetime factory-bot

我的一个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

我认为这与夏令时或其他事情有关?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

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

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

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


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