开发者

Rails time formatting test failing because it's one hour off?

开发者 https://www.devze.com 2023-03-28 03:15 出处:网络
I have the following method in one of my Rails classes: def human_departure_time \"#{departure_time.strftime(\"%A, %d %B %Y\")} at #{departure_time.strftime(\"%I:%M %p\")}\"

I have the following method in one of my Rails classes:

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

As you can see, it just takes a datetime attribute of the model and formats it so that it is more human friendly.

Anyway, I have the following test for this method:

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

Pretty simple but the test fails by one hour with the following output:

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"开发者_Go百科 (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)>'

Here is my bus factory just incase that is important. I'm overwriting the departure time with the frozen time plus one hour in my test.

factory :bus do
  origin_name "Drogheda"
  event_name "EP"
  departure_time { DateTime.now + 14.days }
end

I assume this is something to do with daylight savings time or something? How can I fix this issue?


ActiveRecord could be automatically converting time attributes in your model to local time.

You can try and use the %Z parameter of strftime to see the time zone of the outputted timestamp to see where a possible conversion is sneaking into your time.

Some Googled hints that might be relevant:


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


0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号