mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-31 21:37:16 +00:00
Add validator for integer arrays
Example usage:
validates :related_post_ids, integer_array: true
This commit is contained in:
57
spec/validators/integer_array_validator_spec.rb
Normal file
57
spec/validators/integer_array_validator_spec.rb
Normal 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
|
||||
Reference in New Issue
Block a user