Forum: Ruby on Rails How do I deal with ActiveRecord::RecordInvalid: Validation failed:

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ea905398d356c5d6a10bba35b8d16f0c?d=identicon&s=25 Lovell Mcilwain (lmcilwain)
on 2013-08-22 17:25
(Received via mailing list)
Hello all,

I am currently writing model tests in rails 4. I am attempting to add an
error to a reservation object if the total number of reservations for a
given date and time has reached a pre-determined limit.

When my test runs, it is hitting the appropriate code but it is raising
following error as opposed to just giving me an error in the object that
can use.

ActiveRecord::RecordInvalid: Validation failed: Reservation limit
for this time slot

    test/models/reservation_test.rb:29:in `block (2 levels) in

I was wondering if anyone can give me an ideas of how to deal with this.

My test environment is using shoulda, faker, and factory_girl


    setup do

      List.create(name: 'reservation_limit', values: 20)

      @reservation =


should "remove unavailable times if reservation limit for time slot is
full" do

      20.times{ FactoryGirl.create :reservation }

      assert_equal false, FactoryGirl.create(:reservation), "reservation
was created after total reservation for time slot was reached."



def check_reservation_time

    errors.add(:base, "Can't set reservation to a time before 5pm.") if
parse_time(start_time) < parse_time("17:00")

    errors.add(:base, "Can't set reservation to a time after 8pm.") if
parse_time(start_time) > parse_time("20:00")

    errors.add(:base, "Reservation limit reached for this time slot") if
reservation_limit_reached?(Reservation.where("start_date = ? and
= ?", self.start_date, self.start_time))


  def reservation_limit_reached?(reservations)

    reservations.size >= List.where(name:


I am told I can use `rescue_from ActiveRecord::RecordInvalid` but my
research is pointing me to that only working in the controller so I
sure how that would help me in a model test.

Any ideas or help is appreciated.

Ea905398d356c5d6a10bba35b8d16f0c?d=identicon&s=25 Lovell Mcilwain (lmcilwain)
on 2013-08-22 19:20
(Received via mailing list)
Interesting. I solved the issue finding a post from a person with the
error while trying to test. Issue was that i was trying to create an
invalid object before I could test it. So instead, I assigned a valid
object using Factory girl to a local variable then tested that the save
false and this resolved my issue.
This topic is locked and can not be replied to.