rails rspec expects fails for custom validations

12,647

You have a typo. Add a period to your string:

expect {@ua.save!}.to  raise_error(ActiveRecord::RecordInvalid,'Validation failed: This question is no longer active.')

Note: you currently have in your expectation:

'Validation failed: This question is no longer active'

but need:

'Validation failed: This question is no longer active.'

so that it matches your validation string:

'This question is no longer active.'

Share:
12,647
Nicolo77
Author by

Nicolo77

Updated on June 17, 2022

Comments

  • Nicolo77
    Nicolo77 almost 2 years

    I get this error when running my rspec expects with custom validators.

    expect {@ua.save!}.to  raise_error(ActiveRecord::RecordInvalid,'Validation failed: This question is no longer active')
    

    fails with

    expected ActiveRecord::RecordInvalid with "Validation failed: This question is no longer active", got #<ActiveRecord::RecordInvalid: Validation failed: This question is no longer active.> with backtrace:
    

    This only seems to be problem with my custom validations. See this model:

    class UserAnswer < ActiveRecord::Base
      belongs_to :user
      belongs_to :question
      validate :questionIsActive?
    
      private
    
      def questionIsActive?
        errors.add(:base, "This question is no longer active.") if !self.question.is_active?
      end
    end
    

    Using: Rails 3.2.11 Rspec-rails 2.12.2

  • Nicolo77
    Nicolo77 over 11 years
    I knew I was missing something obvious. Thanks