How to test custom Rails Validator

Asked

Viewed 27 times

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 how best to test this validation using Rspec.

1 answer

0


I resolved it that 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.