How to test custom Rails validator

1

Hello, I have the following custom validator

class StatusMappingValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return nil if can_move_to?(record.class::STATUS_MAP, record.status, value)
    record.errors[attribute] << (options[:message] || 'Cannot move to this status')
  end

  def can_move_to?(mapped_status, old_status, new_status)
    mapped_status[old_status].include?(new_status)
  end
end

I would like to know the best way to test this validation using Rspec.

    
asked by anonymous 05.07.2016 / 14:45

1 answer

0

I have decided this way:

require 'rails_helper'
describe StatusMappingValidator do
  let(:status_map) do
    {
      status_a: [:status_b],
      status_b: [:status_c],
      status_c: [:status_b, :status_a]
    }
  end
  let(:validator) { StatusMappingValidator.new({:attributes => {status: nil}}) }

  describe 'validate move' do
    let(:movimentacao) { FactoryGirl.create(:movimentacao) }

    context 'is valid' do
      it "return nil" do
        expect(validator.validate_each(movimentacao, :status, 'enviado')).to be nil
      end
    end

    context 'is invalid' do
      it "return error array" do
        expect(validator.validate_each(movimentacao, :status, 'analisado')).to be_kind_of(Array)
      end
    end

  end

  describe 'can move' do
    it "A to B" do
      expect(validator.can_move_to?(status_map, :status_a, :status_b)).to be true
    end

    it "C to B" do
      expect(validator.can_move_to?(status_map, :status_c, :status_b)).to be true
    end

    it "C to A" do
      expect(validator.can_move_to?(status_map, :status_c, :status_a)).to be true
    end
  end
  describe 'cannot move' do
    it "B to A" do
      expect(validator.can_move_to?(status_map, :status_b, :status_a)).to be false
    end
  end

end
    
05.07.2016 / 16:35