diff --git a/lib/validates_timeliness/conversion.rb b/lib/validates_timeliness/conversion.rb index af9ffb6..81d8468 100644 --- a/lib/validates_timeliness/conversion.rb +++ b/lib/validates_timeliness/conversion.rb @@ -2,7 +2,7 @@ module ValidatesTimeliness module Conversion def type_cast_value(value, type) - return nil if value.nil? + return nil if value.nil? || !value.respond_to?(:to_time) value = value.in_time_zone if value.acts_like?(:time) && @timezone_aware value = case type diff --git a/spec/validates_timeliness/conversion_spec.rb b/spec/validates_timeliness/conversion_spec.rb index 25b6af4..656ff57 100644 --- a/spec/validates_timeliness/conversion_spec.rb +++ b/spec/validates_timeliness/conversion_spec.rb @@ -22,6 +22,10 @@ describe ValidatesTimeliness::Conversion do it "should return date part of datetime value" do type_cast_value(DateTime.new(2010, 1, 1, 0, 0, 0), :date).should == Date.new(2010, 1, 1) end + + it 'should return nil for invalid value types' do + type_cast_value(12, :date).should == nil + end end describe "for time type" do @@ -40,6 +44,10 @@ describe ValidatesTimeliness::Conversion do it "should return dummy date with time part for datetime value" do type_cast_value(DateTime.civil_from_format(:utc, 2010, 1, 1, 12, 34, 56), :time).should == Time.utc(2000, 1, 1, 12, 34, 56) end + + it 'should return nil for invalid value types' do + type_cast_value(12, :time).should == nil + end end describe "for datetime type" do @@ -63,6 +71,10 @@ describe ValidatesTimeliness::Conversion do result.should == Time.zone.local(2010, 1, 1, 23, 34, 56) result.zone.should == 'EST' end + + it 'should return nil for invalid value types' do + type_cast_value(12, :datetime).should == nil + end end describe "ignore_usec option" do