1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Add tests for duration multiplication and division

When multiplying or dividing a duration by a scalar, it's tempting to
operate directly on the duration's value in seconds and recompute the
parts from the result. However this loses information, as there are
multiple combinations of parts that map to any given number of seconds
(e.g. `2.weeks` or `336.hours`). This is especially problematic when
dealing with durations on the scale of months or years, as converting an
exact number of seconds to one of those intervals and then using the
resulting duration to modify a date will give the wrong result.
This commit is contained in:
Eugene Kenny 2018-06-25 13:48:35 +01:00
parent b2eb1d1c55
commit 376b687cb7

View file

@ -158,6 +158,18 @@ class DurationTest < ActiveSupport::TestCase
assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 1.day * 2 assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 1.day * 2
end end
def test_date_added_with_multiplied_duration_larger_than_one_month
assert_equal Date.civil(2017, 2, 15), Date.civil(2017, 1, 1) + 1.day * 45
end
def test_date_added_with_divided_duration
assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 4.days / 2
end
def test_date_added_with_divided_duration_larger_than_one_month
assert_equal Date.civil(2017, 2, 15), Date.civil(2017, 1, 1) + 90.days / 2
end
def test_plus_with_time def test_plus_with_time
assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration" assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
end end