Add validator for integer arrays

Example usage:

    validates :related_post_ids, integer_array: true
This commit is contained in:
Kristina Lim
2018-09-21 12:16:06 +08:00
committed by luisramos0
parent de9cff6fc2
commit f6e8f18d89
3 changed files with 123 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
require "spec_helper"
describe IntegerArrayValidator do
class TestModel
include ActiveModel::Validations
attr_accessor :ids
validates :ids, integer_array: true
end
describe "internationalization" do
it "has translation for NOT_ARRAY_ERROR" do
expect(described_class::NOT_ARRAY_ERROR).not_to be_blank
end
it "has translation for INVALID_ELEMENT_ERROR" do
expect(described_class::INVALID_ELEMENT_ERROR).not_to be_blank
end
end
describe "validation" do
let(:instance) { TestModel.new }
it "does not add error when nil" do
instance.ids = nil
expect(instance).to be_valid
end
it "does not add error when blank array" do
instance.ids = []
expect(instance).to be_valid
end
it "adds error NOT_ARRAY_ERROR when neither nil nor an array" do
instance.ids = 1
expect(instance).not_to be_valid
expect(instance.errors[:ids]).to include(described_class::NOT_ARRAY_ERROR)
end
it "does not add error when array of integers" do
instance.ids = [1, 2, 3]
expect(instance).to be_valid
end
it "does not add error when array of integers as String" do
instance.ids = ["1", "2", "3"]
expect(instance).to be_valid
end
it "adds error INVALID_ELEMENT_ERROR when an element cannot be parsed as Integer" do
instance.ids = [1, "2", "Not Integer", 3]
expect(instance).not_to be_valid
expect(instance.errors[:ids]).to include(described_class::INVALID_ELEMENT_ERROR)
end
end
end