-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
-
None
Hi, I'm having issues in MongoId with devise, it is persisting invalid objects into database.
class Client include Mongoid::Document devise :database_authenticatable, :registerable, :validatable, :recoverable, :confirmable ... end class ClientsController < ApplicationController def update_password begin client = Client.find @current_user_credentials[:_id] rescue Mongoid::Errors::DocumentNotFound return render nothing: true, status: :unauthorized end safe_params = params.require(:client).permit( :password, :current_password, :password_confirmation ) pass_keys = %w(password current_password password_confirmation).freeze unless (safe_params.keys & pass_keys) == pass_keys return render nothing: true, status: :ok end unless client.valid_password? safe_params[:current_password] return render json: { errors: client.errors.full_messages }, status: :forbidden end # devise client.password = safe_params[:password] client.password_confirmation = safe_params[:password_confirmation] unless client.save puts client.valid? # => false puts client.password == safe_params[:password] # => true puts client.persisted? # => true (WTF?) return render json: { errors: client.errors.full_messages }, status: :forbidden end render nothing: true, status: :ok end end
and if I instead use client.save! it raise an exception but that's not what I want.
Failure/Error: put :update_password, client: { Mongoid::Errors::Validations: Problem: Validation of Client failed. Summary: The following errors were found: Password confirmation doesn't match Password Resolution: Try persisting the document with valid data or remove the validations.
the test
let(:client) do FactoryGirl.create_for :client end it 'should not be able to update password' do jwt_validate_token client put :update_password, client: { current_password: client.password, password: 'passwordpassword2', password_confirmation: 'passwordpassword' }, id: client._id.to_s, format: :json expect(response.status).to eql 403 response_body = JSON.parse(response.body, symbolize_names: true) expect(response_body[:errors]).to include 'Password confirmation doesn\'t match Password' c_client = Client.find client._id expect(c_client.valid_password? client.password).to be true # expected true got false end