From b8b089ef11300fab4625011b942ee4a1fbbdbbbd Mon Sep 17 00:00:00 2001 From: Matt Rohrer Date: Thu, 21 Sep 2017 15:39:49 +0200 Subject: Allow passing a Proc or Symbol as an argument to length validator values This brings the Length validator in line with the Numericality validator, which currently supports Proc & Symbol arguments --- .../cases/validations/length_validation_test.rb | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'activemodel/test') diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb index a0d8e058f5..42f76f3e3c 100644 --- a/activemodel/test/cases/validations/length_validation_test.rb +++ b/activemodel/test/cases/validations/length_validation_test.rb @@ -410,4 +410,35 @@ class LengthValidationTest < ActiveModel::TestCase assert Topic.new("title" => "david").valid? assert Topic.new("title" => "david2").invalid? end + + def test_validates_length_of_using_proc_as_maximum + Topic.validates_length_of :title, maximum: ->(model) { 5 } + + t = Topic.new("title" => "valid", "content" => "whatever") + assert t.valid? + + t.title = "notvalid" + assert t.invalid? + assert t.errors[:title].any? + assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title] + + t.title = "" + assert t.valid? + end + + def test_validates_length_of_using_proc_as_maximum_with_model_method + Topic.send(:define_method, :max_title_length, lambda { 5 }) + Topic.validates_length_of :title, maximum: Proc.new(&:max_title_length) + + t = Topic.new("title" => "valid", "content" => "whatever") + assert t.valid? + + t.title = "notvalid" + assert t.invalid? + assert t.errors[:title].any? + assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title] + + t.title = "" + assert t.valid? + end end -- cgit v1.2.3