0

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??

  • Please check this https://stackoverflow.com/questions/20999426/how-to-write-down-the-rspec-to-test-rescue-block, this might be solve your issue. – Hardik Upadhyay Feb 10 '20 at 05:46
  • sorry, that is not what i'm looking for. I need to set valid? to false to keep consistency in my tests – Alejandro Zaizar Feb 10 '20 at 06:00
  • If you see an error, always post a backtrace as well. Looking at the backtrace may help you to fix your issue by yourself too. – akostadinov Jan 26 '22 at 18:43

0 Answers0