0
votes

I am using devise gem(authentication). I am implementing custom validation for reset password. User can not reset there new password with existing password. in user model code is:

 class User < ActiveRecord::Base
     include ActiveModel::ForbiddenAttributesProtection
     validate  :check_existed_password                               

      def check_existed_password
        if User.find_by_email(self.email).valid_password?(password)
          errors.add(:password, "password already existed, try other")
        end
      end
    end                               

After running rspec, I am getting error: Failure/Error: no_email_user.should_not be_valid NoMethodError: undefined method `valid_password?' for nil:NilClass. All pre-existing test cases in user_spec.rb file is getting fail. any suggestion ?

Blockquote

1
Which Rails version you are using? - Pavan

1 Answers

0
votes

Either the email is not present or the email you are providing doesn't has any user associated with it. This is why you are geeting the error. As in the spec you are checking no_email_user.should_not be_valid means user with no email should not be valid. The validation you have added check_existed_password needs to only run on update and not on create. So make it as:

validate  :check_existed_password, :on => :update

Beacuse the user will reset password on update action and not on create. Currently it will try to find a user which has not been created yet and throw error everytime.

Hope this helps.