I'm working on a refactor for some ruby on rails v6 application. I have made a custom validator to test if the string being passed could be parsed into a Date object, like so:
class DateFormatValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any? do |field|
if record.send(field).nil?
return true
end
unless valid_date?(record.send(field))
record.errors.add(field, :invalid)
return false
end
end
end
end
def valid_date?(date_string)
Date.parse(date_string)
true
rescue ArgumentError
false
end
end
It is being called, and it adds the error to the record with the correct key for the field i'm passing. It is being called like so from inside my model:
validates_with DateFormatValidator, fields: [:date_of_birth]
But, when I ran a test to failed that parser like this:
def test_it_raises_ArgumentError_due_to_invalid_date
customer = customers(:one)
assert_raises(ArgumentError) do
customer.update({date_of_birth: "18/0-8/1989"})
end
end
Now, the assert_raises is my problem. I would expect to be able to do customer.valid? and since an error has been added to the customer it would return false. But instead, it returns:
ArgumentError: invalid date
Any ideas of what am I doing wrong or how to make the valid? turn false when i add an error into the errors obj holding my record??