5
require 'models/person'
6
require 'models/developer'
7
require 'models/warehouse_thing'
11
require 'models/event'
13
# The following methods in Topic are used in test_conditional_validation_*
15
has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
16
has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
22
def condition_is_true_but_its_not
27
class ProtectedPerson < ActiveRecord::Base
28
set_table_name 'people'
30
attr_protected :first_name
33
this_method_does_not_exist!
35
errors.add(:special_error, "This method does not exist")
39
class UniqueReply < Reply
40
validates_uniqueness_of :content, :scope => 'parent_id'
43
class SillyUniqueReply < UniqueReply
46
class Wizard < ActiveRecord::Base
47
self.abstract_class = true
49
validates_uniqueness_of :name
52
class IneptWizard < Wizard
53
validates_uniqueness_of :city
56
class Conjurer < IneptWizard
59
class Thaumaturgist < IneptWizard
63
class ValidationsTest < ActiveRecord::TestCase
64
fixtures :topics, :developers, 'warehouse-things'
66
# Most of the tests mess with the validations of Topic, so lets repair it all the time.
67
# Other classes we mess with will be dealt with in the specific tests
68
repair_validations(Topic)
70
def test_single_field_validation
72
r.title = "There's no content!"
73
assert !r.valid?, "A reply without content shouldn't be saveable"
75
r.content = "Messa content!"
76
assert r.valid?, "A reply with content should be saveable"
79
def test_single_attr_validation_and_error_msg
81
r.title = "There's no content!"
83
assert r.errors.invalid?("content"), "A reply without content should mark that attribute as invalid"
84
assert_equal "Empty", r.errors.on("content"), "A reply without content should contain an error"
85
assert_equal 1, r.errors.count
88
def test_double_attr_validation_and_error_msg
92
assert r.errors.invalid?("title"), "A reply without title should mark that attribute as invalid"
93
assert_equal "Empty", r.errors.on("title"), "A reply without title should contain an error"
95
assert r.errors.invalid?("content"), "A reply without content should mark that attribute as invalid"
96
assert_equal "Empty", r.errors.on("content"), "A reply without content should contain an error"
98
assert_equal 2, r.errors.count
101
def test_error_on_create
103
r.title = "Wrong Create"
105
assert r.errors.invalid?("title"), "A reply with a bad title should mark that attribute as invalid"
106
assert_equal "is Wrong Create", r.errors.on("title"), "A reply with a bad content should contain an error"
109
def test_error_on_update
113
assert r.save, "First save should be successful"
115
r.title = "Wrong Update"
116
assert !r.save, "Second save should fail"
118
assert r.errors.invalid?("title"), "A reply with a bad title should mark that attribute as invalid"
119
assert_equal "is Wrong Update", r.errors.on("title"), "A reply with a bad content should contain an error"
122
def test_invalid_record_exception
123
assert_raise(ActiveRecord::RecordInvalid) { Reply.create! }
124
assert_raise(ActiveRecord::RecordInvalid) { Reply.new.save! }
130
rescue ActiveRecord::RecordInvalid => invalid
131
assert_equal r, invalid.record
135
def test_exception_on_create_bang_many
136
assert_raise(ActiveRecord::RecordInvalid) do
137
Reply.create!([ { "title" => "OK" }, { "title" => "Wrong Create" }])
141
def test_exception_on_create_bang_with_block
142
assert_raise(ActiveRecord::RecordInvalid) do
143
Reply.create!({ "title" => "OK" }) do |r|
149
def test_exception_on_create_bang_many_with_block
150
assert_raise(ActiveRecord::RecordInvalid) do
151
Reply.create!([{ "title" => "OK" }, { "title" => "Wrong Create" }]) do |r|
157
def test_scoped_create_without_attributes
158
Reply.with_scope(:create => {}) do
159
assert_raise(ActiveRecord::RecordInvalid) { Reply.create! }
163
def test_create_with_exceptions_using_scope_for_protected_attributes
164
assert_nothing_raised do
165
ProtectedPerson.with_scope( :create => { :first_name => "Mary" } ) do
166
person = ProtectedPerson.create! :addon => "Addon"
167
assert_equal person.first_name, "Mary", "scope should ignore attr_protected"
172
def test_create_with_exceptions_using_scope_and_empty_attributes
173
assert_nothing_raised do
174
ProtectedPerson.with_scope( :create => { :first_name => "Mary" } ) do
175
person = ProtectedPerson.create!
176
assert_equal person.first_name, "Mary", "should be ok when no attributes are passed to create!"
181
def test_values_are_not_retrieved_unless_needed
182
assert_nothing_raised do
183
person = ProtectedPerson.new
185
assert_equal "This method does not exist", person.errors[:special_error]
189
def test_single_error_per_attr_iteration
194
r.errors.each { |attr, msg| errors << [attr, msg] }
196
assert errors.include?(["title", "Empty"])
197
assert errors.include?(["content", "Empty"])
200
def test_multiple_errors_per_attr_iteration_with_full_error_composition
202
r.title = "Wrong Create"
203
r.content = "Mismatch"
207
r.errors.each_full { |error| errors << error }
209
assert_equal "Title is Wrong Create", errors[0]
210
assert_equal "Title is Content Mismatch", errors[1]
211
assert_equal 2, r.errors.count
214
def test_errors_on_base
216
r.content = "Mismatch"
218
r.errors.add_to_base "Reply is not dignifying"
221
r.errors.each_full { |error| errors << error }
223
assert_equal "Reply is not dignifying", r.errors.on_base
225
assert errors.include?("Title Empty")
226
assert errors.include?("Reply is not dignifying")
227
assert_equal 2, r.errors.count
230
def test_create_without_validation
233
assert reply.save(false)
236
def test_create_without_validation_bang
238
assert_nothing_raised { Reply.new.save_without_validation! }
239
assert count+1, Reply.count
242
def test_validates_each
244
Topic.validates_each(:title, :content, [:title, :content]) do |record, attr|
245
record.errors.add attr, 'gotcha'
248
t = Topic.new("title" => "valid", "content" => "whatever")
251
assert_equal %w(gotcha gotcha), t.errors.on(:title)
252
assert_equal %w(gotcha gotcha), t.errors.on(:content)
255
def test_no_title_confirmation
256
Topic.validates_confirmation_of(:title)
258
t = Topic.new(:author_name => "Plutarch")
261
t.title_confirmation = "Parallel Lives"
264
t.title_confirmation = nil
265
t.title = "Parallel Lives"
268
t.title_confirmation = "Parallel Lives"
272
def test_title_confirmation
273
Topic.validates_confirmation_of(:title)
275
t = Topic.create("title" => "We should be confirmed","title_confirmation" => "")
278
t.title_confirmation = "We should be confirmed"
282
def test_terms_of_service_agreement_no_acceptance
283
Topic.validates_acceptance_of(:terms_of_service, :on => :create)
285
t = Topic.create("title" => "We should not be confirmed")
289
def test_terms_of_service_agreement
290
Topic.validates_acceptance_of(:terms_of_service, :on => :create)
292
t = Topic.create("title" => "We should be confirmed","terms_of_service" => "")
294
assert_equal "must be accepted", t.errors.on(:terms_of_service)
296
t.terms_of_service = "1"
302
Topic.validates_acceptance_of(:eula, :message => "must be abided", :on => :create)
304
t = Topic.create("title" => "We should be confirmed","eula" => "")
306
assert_equal "must be abided", t.errors.on(:eula)
312
def test_terms_of_service_agreement_with_accept_value
313
Topic.validates_acceptance_of(:terms_of_service, :on => :create, :accept => "I agree.")
315
t = Topic.create("title" => "We should be confirmed", "terms_of_service" => "")
317
assert_equal "must be accepted", t.errors.on(:terms_of_service)
319
t.terms_of_service = "I agree."
323
def test_validates_acceptance_of_as_database_column
324
repair_validations(Reply) do
325
Reply.validates_acceptance_of(:author_name)
327
reply = Reply.create("author_name" => "Dan Brown")
328
assert_equal "Dan Brown", reply["author_name"]
332
def test_validates_acceptance_of_with_non_existant_table
333
Object.const_set :IncorporealModel, Class.new(ActiveRecord::Base)
335
assert_nothing_raised ActiveRecord::StatementInvalid do
336
IncorporealModel.validates_acceptance_of(:incorporeal_column)
340
def test_validate_presences
341
Topic.validates_presence_of(:title, :content)
345
assert_equal "can't be blank", t.errors.on(:title)
346
assert_equal "can't be blank", t.errors.on(:content)
348
t.title = "something"
352
assert_equal "can't be blank", t.errors.on(:content)
354
t.content = "like stuff"
359
def test_validate_uniqueness
360
Topic.validates_uniqueness_of(:title)
362
t = Topic.new("title" => "I'm uniquƩ!")
363
assert t.save, "Should save t as unique"
365
t.content = "Remaining unique"
366
assert t.save, "Should still save t as unique"
368
t2 = Topic.new("title" => "I'm uniquƩ!")
369
assert !t2.valid?, "Shouldn't be valid"
370
assert !t2.save, "Shouldn't save t2 as unique"
371
assert_equal "has already been taken", t2.errors.on(:title)
373
t2.title = "Now Im really also unique"
374
assert t2.save, "Should now save t2 as unique"
377
def test_validates_uniquness_with_newline_chars
378
Topic.validates_uniqueness_of(:title, :case_sensitive => false)
380
t = Topic.new("title" => "new\nline")
381
assert t.save, "Should save t as unique"
384
def test_validate_uniqueness_with_scope
385
repair_validations(Reply) do
386
Reply.validates_uniqueness_of(:content, :scope => "parent_id")
388
t = Topic.create("title" => "I'm unique!")
390
r1 = t.replies.create "title" => "r1", "content" => "hello world"
391
assert r1.valid?, "Saving r1"
393
r2 = t.replies.create "title" => "r2", "content" => "hello world"
394
assert !r2.valid?, "Saving r2 first time"
396
r2.content = "something else"
397
assert r2.save, "Saving r2 second time"
399
t2 = Topic.create("title" => "I'm unique too!")
400
r3 = t2.replies.create "title" => "r3", "content" => "hello world"
401
assert r3.valid?, "Saving r3"
405
def test_validate_uniqueness_scoped_to_defining_class
406
t = Topic.create("title" => "What, me worry?")
408
r1 = t.unique_replies.create "title" => "r1", "content" => "a barrel of fun"
409
assert r1.valid?, "Saving r1"
411
r2 = t.silly_unique_replies.create "title" => "r2", "content" => "a barrel of fun"
412
assert !r2.valid?, "Saving r2"
414
# Should succeed as validates_uniqueness_of only applies to
415
# UniqueReply and its subclasses
416
r3 = t.replies.create "title" => "r2", "content" => "a barrel of fun"
417
assert r3.valid?, "Saving r3"
420
def test_validate_uniqueness_with_scope_array
421
repair_validations(Reply) do
422
Reply.validates_uniqueness_of(:author_name, :scope => [:author_email_address, :parent_id])
424
t = Topic.create("title" => "The earth is actually flat!")
426
r1 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy@rubyonrails.com", "title" => "You're crazy!", "content" => "Crazy reply"
427
assert r1.valid?, "Saving r1"
429
r2 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy@rubyonrails.com", "title" => "You're crazy!", "content" => "Crazy reply again..."
430
assert !r2.valid?, "Saving r2. Double reply by same author."
432
r2.author_email_address = "jeremy_alt_email@rubyonrails.com"
433
assert r2.save, "Saving r2 the second time."
435
r3 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy_alt_email@rubyonrails.com", "title" => "You're wrong", "content" => "It's cubic"
436
assert !r3.valid?, "Saving r3"
438
r3.author_name = "jj"
439
assert r3.save, "Saving r3 the second time."
441
r3.author_name = "jeremy"
442
assert !r3.save, "Saving r3 the third time."
446
def test_validate_case_insensitive_uniqueness
447
Topic.validates_uniqueness_of(:title, :parent_id, :case_sensitive => false, :allow_nil => true)
449
t = Topic.new("title" => "I'm unique!", :parent_id => 2)
450
assert t.save, "Should save t as unique"
452
t.content = "Remaining unique"
453
assert t.save, "Should still save t as unique"
455
t2 = Topic.new("title" => "I'm UNIQUE!", :parent_id => 1)
456
assert !t2.valid?, "Shouldn't be valid"
457
assert !t2.save, "Shouldn't save t2 as unique"
458
assert t2.errors.on(:title)
459
assert t2.errors.on(:parent_id)
460
assert_equal "has already been taken", t2.errors.on(:title)
462
t2.title = "I'm truly UNIQUE!"
463
assert !t2.valid?, "Shouldn't be valid"
464
assert !t2.save, "Shouldn't save t2 as unique"
465
assert_nil t2.errors.on(:title)
466
assert t2.errors.on(:parent_id)
469
assert t2.save, "Should now save t2 as unique"
473
assert t2.valid?, "should validate with nil"
474
assert t2.save, "should save with nil"
476
with_kcode('UTF8') do
477
t_utf8 = Topic.new("title" => "ŠÆ ŃŠ¾Š¶Šµ ŃŠ½ŠøŠŗŠ°Š»ŃŠ½ŃŠ¹!")
478
assert t_utf8.save, "Should save t_utf8 as unique"
480
# If database hasn't UTF-8 character set, this test fails
481
if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "Ń ŃŠ¾Š¶Šµ ŃŠ½ŠøŠŗŠ°Š»ŃŠ½ŃŠ¹!"
482
t2_utf8 = Topic.new("title" => "Ń ŃŠ¾Š¶Šµ Š£ŠŠŠŠŠŠ¬ŠŠ«Š!")
483
assert !t2_utf8.valid?, "Shouldn't be valid"
484
assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique"
489
def test_validate_case_sensitive_uniqueness
490
Topic.validates_uniqueness_of(:title, :case_sensitive => true, :allow_nil => true)
492
t = Topic.new("title" => "I'm unique!")
493
assert t.save, "Should save t as unique"
495
t.content = "Remaining unique"
496
assert t.save, "Should still save t as unique"
498
t2 = Topic.new("title" => "I'M UNIQUE!")
499
assert t2.valid?, "Should be valid"
500
assert t2.save, "Should save t2 as unique"
501
assert !t2.errors.on(:title)
502
assert !t2.errors.on(:parent_id)
503
assert_not_equal "has already been taken", t2.errors.on(:title)
505
t3 = Topic.new("title" => "I'M uNiQUe!")
506
assert t3.valid?, "Should be valid"
507
assert t3.save, "Should save t2 as unique"
508
assert !t3.errors.on(:title)
509
assert !t3.errors.on(:parent_id)
510
assert_not_equal "has already been taken", t3.errors.on(:title)
513
def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
514
Topic.validates_uniqueness_of(:title, :case_sensitve => true)
515
t = Topic.create!('title' => 101)
517
t2 = Topic.new('title' => 101)
519
assert t2.errors.on(:title)
522
def test_validate_uniqueness_with_non_standard_table_names
523
i1 = WarehouseThing.create(:value => 1000)
524
assert !i1.valid?, "i1 should not be valid"
525
assert i1.errors.on(:value), "Should not be empty"
528
def test_validates_uniqueness_inside_with_scope
529
Topic.validates_uniqueness_of(:title)
531
Topic.with_scope(:find => { :conditions => { :author_name => "David" } }) do
532
t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary")
534
t2 = Topic.new("title" => "I'm unique!", "author_name" => "David")
539
def test_validate_uniqueness_with_columns_which_are_sql_keywords
540
repair_validations(Guid) do
541
Guid.validates_uniqueness_of :key
544
assert_nothing_raised { !g.valid? }
548
def test_validate_uniqueness_with_limit
549
# Event.title is limited to 5 characters
550
e1 = Event.create(:title => "abcde")
551
assert e1.valid?, "Could not create an event with a unique, 5 character title"
552
e2 = Event.create(:title => "abcdefgh")
553
assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique"
556
def test_validate_uniqueness_with_limit_and_utf8
557
with_kcode('UTF8') do
558
# Event.title is limited to 5 characters
559
e1 = Event.create(:title => "äøäŗäøåäŗ")
560
assert e1.valid?, "Could not create an event with a unique, 5 character title"
561
e2 = Event.create(:title => "äøäŗäøåäŗå
äøå
«")
562
assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique"
566
def test_validate_straight_inheritance_uniqueness
567
w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork")
568
assert w1.valid?, "Saving w1"
570
# Should use validation from base class (which is abstract)
571
w2 = IneptWizard.new(:name => "Rincewind", :city => "Quirm")
572
assert !w2.valid?, "w2 shouldn't be valid"
573
assert w2.errors.on(:name), "Should have errors for name"
574
assert_equal "has already been taken", w2.errors.on(:name), "Should have uniqueness message for name"
576
w3 = Conjurer.new(:name => "Rincewind", :city => "Quirm")
577
assert !w3.valid?, "w3 shouldn't be valid"
578
assert w3.errors.on(:name), "Should have errors for name"
579
assert_equal "has already been taken", w3.errors.on(:name), "Should have uniqueness message for name"
581
w4 = Conjurer.create(:name => "The Amazing Bonko", :city => "Quirm")
582
assert w4.valid?, "Saving w4"
584
w5 = Thaumaturgist.new(:name => "The Amazing Bonko", :city => "Lancre")
585
assert !w5.valid?, "w5 shouldn't be valid"
586
assert w5.errors.on(:name), "Should have errors for name"
587
assert_equal "has already been taken", w5.errors.on(:name), "Should have uniqueness message for name"
589
w6 = Thaumaturgist.new(:name => "Mustrum Ridcully", :city => "Quirm")
590
assert !w6.valid?, "w6 shouldn't be valid"
591
assert w6.errors.on(:city), "Should have errors for city"
592
assert_equal "has already been taken", w6.errors.on(:city), "Should have uniqueness message for city"
595
def test_validate_format
596
Topic.validates_format_of(:title, :content, :with => /^Validation\smacros \w+!$/, :message => "is bad data")
598
t = Topic.create("title" => "i'm incorrect", "content" => "Validation macros rule!")
599
assert !t.valid?, "Shouldn't be valid"
600
assert !t.save, "Shouldn't save because it's invalid"
601
assert_equal "is bad data", t.errors.on(:title)
602
assert_nil t.errors.on(:content)
604
t.title = "Validation macros rule!"
607
assert_nil t.errors.on(:title)
609
assert_raise(ArgumentError) { Topic.validates_format_of(:title, :content) }
612
def test_validate_format_with_allow_blank
613
Topic.validates_format_of(:title, :with => /^Validation\smacros \w+!$/, :allow_blank=>true)
614
assert !Topic.create("title" => "Shouldn't be valid").valid?
615
assert Topic.create("title" => "").valid?
616
assert Topic.create("title" => nil).valid?
617
assert Topic.create("title" => "Validation macros rule!").valid?
620
# testing ticket #3142
621
def test_validate_format_numeric
622
Topic.validates_format_of(:title, :content, :with => /^[1-9][0-9]*$/, :message => "is bad data")
624
t = Topic.create("title" => "72x", "content" => "6789")
625
assert !t.valid?, "Shouldn't be valid"
626
assert !t.save, "Shouldn't save because it's invalid"
627
assert_equal "is bad data", t.errors.on(:title)
628
assert_nil t.errors.on(:content)
631
assert !t.valid?, "Shouldn't be valid"
634
assert !t.valid?, "Shouldn't be valid"
637
assert !t.valid?, "Shouldn't be valid"
640
assert !t.valid?, "Shouldn't be valid"
645
assert_nil t.errors.on(:title)
648
def test_validate_format_with_formatted_message
649
Topic.validates_format_of(:title, :with => /^Valid Title$/, :message => "can't be {{value}}")
650
t = Topic.create(:title => 'Invalid title')
651
assert_equal "can't be Invalid title", t.errors.on(:title)
654
def test_validates_inclusion_of
655
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
657
assert !Topic.create("title" => "a!", "content" => "abc").valid?
658
assert !Topic.create("title" => "a b", "content" => "abc").valid?
659
assert !Topic.create("title" => nil, "content" => "def").valid?
661
t = Topic.create("title" => "a", "content" => "I know you are but what am I?")
665
assert t.errors.on(:title)
666
assert_equal "is not included in the list", t.errors["title"]
668
assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => nil ) }
669
assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => 0) }
671
assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => "hi!" ) }
672
assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => {} ) }
673
assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => [] ) }
676
def test_validates_inclusion_of_with_allow_nil
677
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :allow_nil=>true )
679
assert !Topic.create("title" => "a!", "content" => "abc").valid?
680
assert !Topic.create("title" => "", "content" => "abc").valid?
681
assert Topic.create("title" => nil, "content" => "abc").valid?
684
def test_numericality_with_getter_method
685
repair_validations(Developer) do
686
Developer.validates_numericality_of( :salary )
687
developer = Developer.new("name" => "michael", "salary" => nil)
688
developer.instance_eval("def salary; read_attribute('salary') ? read_attribute('salary') : 100000; end")
689
assert developer.valid?
693
def test_validates_length_of_with_allow_nil
694
Topic.validates_length_of( :title, :is => 5, :allow_nil=>true )
696
assert !Topic.create("title" => "ab").valid?
697
assert !Topic.create("title" => "").valid?
698
assert Topic.create("title" => nil).valid?
699
assert Topic.create("title" => "abcde").valid?
702
def test_validates_length_of_with_allow_blank
703
Topic.validates_length_of( :title, :is => 5, :allow_blank=>true )
705
assert !Topic.create("title" => "ab").valid?
706
assert Topic.create("title" => "").valid?
707
assert Topic.create("title" => nil).valid?
708
assert Topic.create("title" => "abcde").valid?
711
def test_validates_inclusion_of_with_formatted_message
712
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :message => "option {{value}} is not in the list" )
714
assert Topic.create("title" => "a", "content" => "abc").valid?
716
t = Topic.create("title" => "uhoh", "content" => "abc")
718
assert t.errors.on(:title)
719
assert_equal "option uhoh is not in the list", t.errors["title"]
722
def test_numericality_with_allow_nil_and_getter_method
723
repair_validations(Developer) do
724
Developer.validates_numericality_of( :salary, :allow_nil => true)
725
developer = Developer.new("name" => "michael", "salary" => nil)
726
developer.instance_eval("def salary; read_attribute('salary') ? read_attribute('salary') : 100000; end")
727
assert developer.valid?
731
def test_validates_exclusion_of
732
Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) )
734
assert Topic.create("title" => "something", "content" => "abc").valid?
735
assert !Topic.create("title" => "monkey", "content" => "abc").valid?
738
def test_validates_exclusion_of_with_formatted_message
739
Topic.validates_exclusion_of( :title, :in => %w( abe monkey ), :message => "option {{value}} is restricted" )
741
assert Topic.create("title" => "something", "content" => "abc")
743
t = Topic.create("title" => "monkey")
745
assert t.errors.on(:title)
746
assert_equal "option monkey is restricted", t.errors["title"]
749
def test_validates_length_of_using_minimum
750
Topic.validates_length_of :title, :minimum => 5
752
t = Topic.create("title" => "valid", "content" => "whatever")
757
assert t.errors.on(:title)
758
assert_equal "is too short (minimum is 5 characters)", t.errors["title"]
762
assert t.errors.on(:title)
763
assert_equal "is too short (minimum is 5 characters)", t.errors["title"]
767
assert t.errors.on(:title)
768
assert_equal "is too short (minimum is 5 characters)", t.errors["title"]
771
def test_optionally_validates_length_of_using_minimum
772
Topic.validates_length_of :title, :minimum => 5, :allow_nil => true
774
t = Topic.create("title" => "valid", "content" => "whatever")
781
def test_validates_length_of_using_maximum
782
Topic.validates_length_of :title, :maximum => 5
784
t = Topic.create("title" => "valid", "content" => "whatever")
789
assert t.errors.on(:title)
790
assert_equal "is too long (maximum is 5 characters)", t.errors["title"]
799
def test_optionally_validates_length_of_using_maximum
800
Topic.validates_length_of :title, :maximum => 5, :allow_nil => true
802
t = Topic.create("title" => "valid", "content" => "whatever")
809
def test_validates_length_of_using_within
810
Topic.validates_length_of(:title, :content, :within => 3..5)
812
t = Topic.new("title" => "a!", "content" => "I'm ooooooooh so very long")
814
assert_equal "is too short (minimum is 3 characters)", t.errors.on(:title)
815
assert_equal "is too long (maximum is 5 characters)", t.errors.on(:content)
820
assert_equal "is too short (minimum is 3 characters)", t.errors.on(:title)
821
assert_equal "is too short (minimum is 3 characters)", t.errors.on(:content)
828
def test_optionally_validates_length_of_using_within
829
Topic.validates_length_of :title, :content, :within => 3..5, :allow_nil => true
831
t = Topic.create('title' => 'abc', 'content' => 'abcd')
838
def test_optionally_validates_length_of_using_within_on_create
839
Topic.validates_length_of :title, :content, :within => 5..10, :on => :create, :too_long => "my string is too long: {{count}}"
841
t = Topic.create("title" => "thisisnotvalid", "content" => "whatever")
843
assert t.errors.on(:title)
844
assert_equal "my string is too long: 10", t.errors[:title]
846
t.title = "butthisis"
852
t.content = "andthisislong"
855
t.content = t.title = "iamfine"
859
def test_optionally_validates_length_of_using_within_on_update
860
Topic.validates_length_of :title, :content, :within => 5..10, :on => :update, :too_short => "my string is too short: {{count}}"
862
t = Topic.create("title" => "vali", "content" => "whatever")
864
assert t.errors.on(:title)
868
assert t.errors.on(:title)
869
assert_equal "my string is too short: 5", t.errors[:title]
872
t.content = "andthisistoolong"
874
assert t.errors.on(:content)
876
t.content = "iamfine"
880
def test_validates_length_of_using_is
881
Topic.validates_length_of :title, :is => 5
883
t = Topic.create("title" => "valid", "content" => "whatever")
888
assert t.errors.on(:title)
889
assert_equal "is the wrong length (should be 5 characters)", t.errors["title"]
898
def test_optionally_validates_length_of_using_is
899
Topic.validates_length_of :title, :is => 5, :allow_nil => true
901
t = Topic.create("title" => "valid", "content" => "whatever")
908
def test_validates_length_of_using_bignum
911
bigrange = bigmin...bigmax
912
assert_nothing_raised do
913
Topic.validates_length_of :title, :is => bigmin + 5
914
Topic.validates_length_of :title, :within => bigrange
915
Topic.validates_length_of :title, :in => bigrange
916
Topic.validates_length_of :title, :minimum => bigmin
917
Topic.validates_length_of :title, :maximum => bigmax
921
def test_validates_length_with_globally_modified_error_message
922
defaults = ActiveSupport::Deprecation.silence { ActiveRecord::Errors.default_error_messages }
923
original_message = defaults[:too_short]
924
defaults[:too_short] = 'tu est trops petit hombre {{count}}'
926
Topic.validates_length_of :title, :minimum => 10
927
t = Topic.create(:title => 'too short')
930
assert_equal 'tu est trops petit hombre 10', t.errors['title']
933
defaults[:too_short] = original_message
936
def test_validates_size_of_association
937
repair_validations(Owner) do
938
assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 }
939
o = Owner.new('name' => 'nopets')
941
assert o.errors.on(:pets)
942
pet = o.pets.build('name' => 'apet')
947
def test_validates_size_of_association_using_within
948
repair_validations(Owner) do
949
assert_nothing_raised { Owner.validates_size_of :pets, :within => 1..2 }
950
o = Owner.new('name' => 'nopets')
952
assert o.errors.on(:pets)
954
pet = o.pets.build('name' => 'apet')
957
2.times { o.pets.build('name' => 'apet') }
959
assert o.errors.on(:pets)
963
def test_validates_length_of_nasty_params
964
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :minimum=>6, :maximum=>9) }
965
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :within=>6, :maximum=>9) }
966
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :within=>6, :minimum=>9) }
967
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :within=>6, :is=>9) }
968
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :minimum=>"a") }
969
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :maximum=>"a") }
970
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :within=>"a") }
971
assert_raise(ArgumentError) { Topic.validates_length_of(:title, :is=>"a") }
974
def test_validates_length_of_custom_errors_for_minimum_with_message
975
Topic.validates_length_of( :title, :minimum=>5, :message=>"boo {{count}}" )
976
t = Topic.create("title" => "uhoh", "content" => "whatever")
978
assert t.errors.on(:title)
979
assert_equal "boo 5", t.errors["title"]
982
def test_validates_length_of_custom_errors_for_minimum_with_too_short
983
Topic.validates_length_of( :title, :minimum=>5, :too_short=>"hoo {{count}}" )
984
t = Topic.create("title" => "uhoh", "content" => "whatever")
986
assert t.errors.on(:title)
987
assert_equal "hoo 5", t.errors["title"]
990
def test_validates_length_of_custom_errors_for_maximum_with_message
991
Topic.validates_length_of( :title, :maximum=>5, :message=>"boo {{count}}" )
992
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
994
assert t.errors.on(:title)
995
assert_equal "boo 5", t.errors["title"]
998
def test_validates_length_of_custom_errors_for_in
999
Topic.validates_length_of(:title, :in => 10..20, :message => "hoo {{count}}")
1000
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1002
assert t.errors.on(:title)
1003
assert_equal "hoo 10", t.errors["title"]
1005
t = Topic.create("title" => "uhohuhohuhohuhohuhohuhohuhohuhoh", "content" => "whatever")
1007
assert t.errors.on(:title)
1008
assert_equal "hoo 20", t.errors["title"]
1011
def test_validates_length_of_custom_errors_for_maximum_with_too_long
1012
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}" )
1013
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1015
assert t.errors.on(:title)
1016
assert_equal "hoo 5", t.errors["title"]
1019
def test_validates_length_of_custom_errors_for_is_with_message
1020
Topic.validates_length_of( :title, :is=>5, :message=>"boo {{count}}" )
1021
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1023
assert t.errors.on(:title)
1024
assert_equal "boo 5", t.errors["title"]
1027
def test_validates_length_of_custom_errors_for_is_with_wrong_length
1028
Topic.validates_length_of( :title, :is=>5, :wrong_length=>"hoo {{count}}" )
1029
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1031
assert t.errors.on(:title)
1032
assert_equal "hoo 5", t.errors["title"]
1035
def test_validates_length_of_using_minimum_utf8
1036
with_kcode('UTF8') do
1037
Topic.validates_length_of :title, :minimum => 5
1039
t = Topic.create("title" => "äøäŗäøåäŗ", "content" => "whatever")
1042
t.title = "äøäŗäøå"
1044
assert t.errors.on(:title)
1045
assert_equal "is too short (minimum is 5 characters)", t.errors["title"]
1049
def test_validates_length_of_using_maximum_utf8
1050
with_kcode('UTF8') do
1051
Topic.validates_length_of :title, :maximum => 5
1053
t = Topic.create("title" => "äøäŗäøåäŗ", "content" => "whatever")
1056
t.title = "äøäŗ34äŗå
"
1058
assert t.errors.on(:title)
1059
assert_equal "is too long (maximum is 5 characters)", t.errors["title"]
1063
def test_validates_length_of_using_within_utf8
1064
with_kcode('UTF8') do
1065
Topic.validates_length_of(:title, :content, :within => 3..5)
1067
t = Topic.new("title" => "äøäŗ", "content" => "12äøåäŗå
äø")
1069
assert_equal "is too short (minimum is 3 characters)", t.errors.on(:title)
1070
assert_equal "is too long (maximum is 5 characters)", t.errors.on(:content)
1071
t.title = "äøäŗäø"
1077
def test_optionally_validates_length_of_using_within_utf8
1078
with_kcode('UTF8') do
1079
Topic.validates_length_of :title, :within => 3..5, :allow_nil => true
1081
t = Topic.create(:title => "äøäŗäøåäŗ")
1082
assert t.valid?, t.errors.inspect
1084
t = Topic.create(:title => "äøäŗäø")
1085
assert t.valid?, t.errors.inspect
1088
assert t.valid?, t.errors.inspect
1092
def test_optionally_validates_length_of_using_within_on_create_utf8
1093
with_kcode('UTF8') do
1094
Topic.validates_length_of :title, :within => 5..10, :on => :create, :too_long => "é·ććć¾ć: {{count}}"
1096
t = Topic.create("title" => "äøäŗäøåäŗå
äøå
«ä¹åA", "content" => "whatever")
1098
assert t.errors.on(:title)
1099
assert_equal "é·ććć¾ć: 10", t.errors[:title]
1101
t.title = "äøäŗäøåäŗå
äøå
«ä¹"
1107
t.content = "äøäŗäøåäŗå
äøå
«ä¹å"
1110
t.content = t.title = "äøäŗäøåäŗå
"
1115
def test_optionally_validates_length_of_using_within_on_update_utf8
1116
with_kcode('UTF8') do
1117
Topic.validates_length_of :title, :within => 5..10, :on => :update, :too_short => "ēććć¾ć: {{count}}"
1119
t = Topic.create("title" => "äøäŗäø4", "content" => "whatever")
1121
assert t.errors.on(:title)
1123
t.title = "1äŗäø4"
1125
assert t.errors.on(:title)
1126
assert_equal "ēććć¾ć: 5", t.errors[:title]
1128
t.title = "äøäŗäøåäŗå
äøå
«ä¹åA"
1130
assert t.errors.on(:title)
1132
t.title = "äøäŗ345"
1137
def test_validates_length_of_using_is_utf8
1138
with_kcode('UTF8') do
1139
Topic.validates_length_of :title, :is => 5
1141
t = Topic.create("title" => "äøäŗ345", "content" => "whatever")
1144
t.title = "äøäŗ345å
"
1146
assert t.errors.on(:title)
1147
assert_equal "is the wrong length (should be 5 characters)", t.errors["title"]
1151
def test_validates_length_of_with_block
1152
Topic.validates_length_of :content, :minimum => 5, :too_short=>"Your essay must be at least {{count}} words.",
1153
:tokenizer => lambda {|str| str.scan(/\w+/) }
1154
t = Topic.create!(:content => "this content should be long enough")
1157
t.content = "not long enough"
1159
assert t.errors.on(:content)
1160
assert_equal "Your essay must be at least 5 words.", t.errors[:content]
1163
def test_validates_size_of_association_utf8
1164
repair_validations(Owner) do
1165
with_kcode('UTF8') do
1166
assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 }
1167
o = Owner.new('name' => 'ćććććććććć')
1169
assert o.errors.on(:pets)
1170
o.pets.build('name' => 'ćććććććććć')
1176
def test_validates_associated_many
1177
Topic.validates_associated( :replies )
1178
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1179
t.replies << [r = Reply.new("title" => "A reply"), r2 = Reply.new("title" => "Another reply", "content" => "non-empty"), r3 = Reply.new("title" => "Yet another reply"), r4 = Reply.new("title" => "The last reply", "content" => "non-empty")]
1181
assert t.errors.on(:replies)
1182
assert_equal 1, r.errors.count # make sure all associated objects have been validated
1183
assert_equal 0, r2.errors.count
1184
assert_equal 1, r3.errors.count
1185
assert_equal 0, r4.errors.count
1186
r.content = r3.content = "non-empty"
1190
def test_validates_associated_one
1191
repair_validations(Reply) do
1192
Reply.validates_associated( :topic )
1193
Topic.validates_presence_of( :content )
1194
r = Reply.new("title" => "A reply", "content" => "with content!")
1195
r.topic = Topic.create("title" => "uhohuhoh")
1197
assert r.errors.on(:topic)
1198
r.topic.content = "non-empty"
1203
def test_validate_block
1204
Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
1205
t = Topic.create("title" => "Title", "content" => "whatever")
1207
assert t.errors.on(:title)
1208
assert_equal "will never be valid", t.errors["title"]
1211
def test_invalid_validator
1213
assert_raise(ArgumentError) { t = Topic.create }
1216
def test_throw_away_typing
1217
d = Developer.new("name" => "David", "salary" => "100,000")
1219
assert_equal 100, d.salary
1220
assert_equal "100,000", d.salary_before_type_cast
1223
def test_validates_acceptance_of_with_custom_error_using_quotes
1224
repair_validations(Developer) do
1225
Developer.validates_acceptance_of :salary, :message=> "This string contains 'single' and \"double\" quotes"
1229
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:salary).last
1233
def test_validates_confirmation_of_with_custom_error_using_quotes
1234
repair_validations(Developer) do
1235
Developer.validates_confirmation_of :name, :message=> "confirm 'single' and \"double\" quotes"
1238
d.name_confirmation = "Johnny"
1240
assert_equal "confirm 'single' and \"double\" quotes", d.errors.on(:name)
1244
def test_validates_format_of_with_custom_error_using_quotes
1245
repair_validations(Developer) do
1246
Developer.validates_format_of :name, :with => /^(A-Z*)$/, :message=> "format 'single' and \"double\" quotes"
1248
d.name = d.name_confirmation = "John 32"
1250
assert_equal "format 'single' and \"double\" quotes", d.errors.on(:name)
1254
def test_validates_inclusion_of_with_custom_error_using_quotes
1255
repair_validations(Developer) do
1256
Developer.validates_inclusion_of :salary, :in => 1000..80000, :message=> "This string contains 'single' and \"double\" quotes"
1260
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:salary).last
1264
def test_validates_length_of_with_custom_too_long_using_quotes
1265
repair_validations(Developer) do
1266
Developer.validates_length_of :name, :maximum => 4, :too_long=> "This string contains 'single' and \"double\" quotes"
1270
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:name)
1274
def test_validates_length_of_with_custom_too_short_using_quotes
1275
repair_validations(Developer) do
1276
Developer.validates_length_of :name, :minimum => 4, :too_short=> "This string contains 'single' and \"double\" quotes"
1280
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:name)
1284
def test_validates_length_of_with_custom_message_using_quotes
1285
repair_validations(Developer) do
1286
Developer.validates_length_of :name, :minimum => 4, :message=> "This string contains 'single' and \"double\" quotes"
1290
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:name)
1294
def test_validates_presence_of_with_custom_message_using_quotes
1295
repair_validations(Developer) do
1296
Developer.validates_presence_of :non_existent, :message=> "This string contains 'single' and \"double\" quotes"
1300
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:non_existent)
1304
def test_validates_uniqueness_of_with_custom_message_using_quotes
1305
repair_validations(Developer) do
1306
Developer.validates_uniqueness_of :name, :message=> "This string contains 'single' and \"double\" quotes"
1310
assert_equal "This string contains 'single' and \"double\" quotes", d.errors.on(:name)
1314
def test_validates_associated_with_custom_message_using_quotes
1315
repair_validations(Reply) do
1316
Reply.validates_associated :topic, :message=> "This string contains 'single' and \"double\" quotes"
1317
Topic.validates_presence_of :content
1318
r = Reply.create("title" => "A reply", "content" => "with content!")
1319
r.topic = Topic.create("title" => "uhohuhoh")
1321
assert_equal "This string contains 'single' and \"double\" quotes", r.errors.on(:topic)
1325
def test_if_validation_using_method_true
1326
# When the method returns true
1327
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :if => :condition_is_true )
1328
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1330
assert t.errors.on(:title)
1331
assert_equal "hoo 5", t.errors["title"]
1334
def test_unless_validation_using_method_true
1335
# When the method returns true
1336
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :unless => :condition_is_true )
1337
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1339
assert !t.errors.on(:title)
1342
def test_if_validation_using_method_false
1343
# When the method returns false
1344
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :if => :condition_is_true_but_its_not )
1345
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1347
assert !t.errors.on(:title)
1350
def test_unless_validation_using_method_false
1351
# When the method returns false
1352
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :unless => :condition_is_true_but_its_not )
1353
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1355
assert t.errors.on(:title)
1356
assert_equal "hoo 5", t.errors["title"]
1359
def test_if_validation_using_string_true
1360
# When the evaluated string returns true
1361
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :if => "a = 1; a == 1" )
1362
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1364
assert t.errors.on(:title)
1365
assert_equal "hoo 5", t.errors["title"]
1368
def test_unless_validation_using_string_true
1369
# When the evaluated string returns true
1370
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :unless => "a = 1; a == 1" )
1371
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1373
assert !t.errors.on(:title)
1376
def test_if_validation_using_string_false
1377
# When the evaluated string returns false
1378
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :if => "false")
1379
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1381
assert !t.errors.on(:title)
1384
def test_unless_validation_using_string_false
1385
# When the evaluated string returns false
1386
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}", :unless => "false")
1387
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1389
assert t.errors.on(:title)
1390
assert_equal "hoo 5", t.errors["title"]
1393
def test_if_validation_using_block_true
1394
# When the block returns true
1395
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}",
1396
:if => Proc.new { |r| r.content.size > 4 } )
1397
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1399
assert t.errors.on(:title)
1400
assert_equal "hoo 5", t.errors["title"]
1403
def test_unless_validation_using_block_true
1404
# When the block returns true
1405
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}",
1406
:unless => Proc.new { |r| r.content.size > 4 } )
1407
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1409
assert !t.errors.on(:title)
1412
def test_if_validation_using_block_false
1413
# When the block returns false
1414
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}",
1415
:if => Proc.new { |r| r.title != "uhohuhoh"} )
1416
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1418
assert !t.errors.on(:title)
1421
def test_unless_validation_using_block_false
1422
# When the block returns false
1423
Topic.validates_length_of( :title, :maximum=>5, :too_long=>"hoo {{count}}",
1424
:unless => Proc.new { |r| r.title != "uhohuhoh"} )
1425
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
1427
assert t.errors.on(:title)
1428
assert_equal "hoo 5", t.errors["title"]
1431
def test_validates_associated_missing
1432
repair_validations(Reply) do
1433
Reply.validates_presence_of(:topic)
1434
r = Reply.create("title" => "A reply", "content" => "with content!")
1436
assert r.errors.on(:topic)
1438
r.topic = Topic.find :first
1443
def test_errors_to_xml
1444
r = Reply.new :title => "Wrong Create"
1446
xml = r.errors.to_xml(:skip_instruct => true)
1447
assert_equal "<errors>", xml.first(8)
1448
assert xml.include?("<error>Title is Wrong Create</error>")
1449
assert xml.include?("<error>Content Empty</error>")
1452
def test_validation_order
1453
Topic.validates_presence_of :title, :author_name
1454
Topic.validate {|topic| topic.errors.add('author_email_address', 'will never be valid')}
1455
Topic.validates_length_of :title, :content, :minimum => 2
1457
t = Topic.new :title => ''
1459
e = t.errors.instance_variable_get '@errors'
1460
assert_equal 'title', key = e.keys.first
1461
assert_equal "can't be blank", t.errors.on(key).first
1462
assert_equal 'is too short (minimum is 2 characters)', t.errors.on(key).second
1463
assert_equal 'author_name', key = e.keys.second
1464
assert_equal "can't be blank", t.errors.on(key)
1465
assert_equal 'author_email_address', key = e.keys.third
1466
assert_equal 'will never be valid', t.errors.on(key)
1467
assert_equal 'content', key = e.keys.fourth
1468
assert_equal 'is too short (minimum is 2 characters)', t.errors.on(key)
1471
def test_invalid_should_be_the_opposite_of_valid
1472
Topic.validates_presence_of :title
1476
assert t.errors.invalid?(:title)
1478
t.title = 'Things are going to change'
1482
# previous implementation of validates_presence_of eval'd the
1483
# string with the wrong binding, this regression test is to
1484
# ensure that it works correctly
1485
def test_validation_with_if_as_string
1486
Topic.validates_presence_of(:title)
1487
Topic.validates_presence_of(:author_name, :if => "title.to_s.match('important')")
1490
assert !t.valid?, "A topic without a title should not be valid"
1491
assert !t.errors.invalid?("author_name"), "A topic without an 'important' title should not require an author"
1493
t.title = "Just a title"
1494
assert t.valid?, "A topic with a basic title should be valid"
1496
t.title = "A very important title"
1497
assert !t.valid?, "A topic with an important title, but without an author, should not be valid"
1498
assert t.errors.invalid?("author_name"), "A topic with an 'important' title should require an author"
1500
t.author_name = "Hubert J. Farnsworth"
1501
assert t.valid?, "A topic with an important title and author should be valid"
1506
class ValidatesNumericalityTest < ActiveRecord::TestCase
1508
BLANK = ["", " ", " \t \r \n"]
1509
BIGDECIMAL_STRINGS = %w(12345678901234567890.1234567890) # 30 significent digits
1510
FLOAT_STRINGS = %w(0.0 +0.0 -0.0 10.0 10.5 -10.5 -0.0001 -090.1 90.1e1 -90.1e5 -90.1e-5 90e-5)
1511
INTEGER_STRINGS = %w(0 +0 -0 10 +10 -10 0090 -090)
1512
FLOATS = [0.0, 10.0, 10.5, -10.5, -0.0001] + FLOAT_STRINGS
1513
INTEGERS = [0, 10, -10] + INTEGER_STRINGS
1514
BIGDECIMAL = BIGDECIMAL_STRINGS.collect! { |bd| BigDecimal.new(bd) }
1515
JUNK = ["not a number", "42 not a number", "0xdeadbeef", "00-1", "--3", "+-3", "+3-1", "-+019.0", "12.12.13.12", "123\nnot a number"]
1516
INFINITY = [1.0/0.0]
1518
repair_validations(Topic)
1520
def test_default_validates_numericality_of
1521
Topic.validates_numericality_of :approved
1523
invalid!(NIL + BLANK + JUNK)
1524
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
1527
def test_validates_numericality_of_with_nil_allowed
1528
Topic.validates_numericality_of :approved, :allow_nil => true
1531
valid!(NIL + BLANK + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
1534
def test_validates_numericality_of_with_integer_only
1535
Topic.validates_numericality_of :approved, :only_integer => true
1537
invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
1541
def test_validates_numericality_of_with_integer_only_and_nil_allowed
1542
Topic.validates_numericality_of :approved, :only_integer => true, :allow_nil => true
1544
invalid!(JUNK + FLOATS + BIGDECIMAL + INFINITY)
1545
valid!(NIL + BLANK + INTEGERS)
1548
def test_validates_numericality_with_greater_than
1549
Topic.validates_numericality_of :approved, :greater_than => 10
1551
invalid!([-10, 10], 'must be greater than 10')
1555
def test_validates_numericality_with_greater_than_or_equal
1556
Topic.validates_numericality_of :approved, :greater_than_or_equal_to => 10
1558
invalid!([-9, 9], 'must be greater than or equal to 10')
1562
def test_validates_numericality_with_equal_to
1563
Topic.validates_numericality_of :approved, :equal_to => 10
1565
invalid!([-10, 11] + INFINITY, 'must be equal to 10')
1569
def test_validates_numericality_with_less_than
1570
Topic.validates_numericality_of :approved, :less_than => 10
1572
invalid!([10], 'must be less than 10')
1576
def test_validates_numericality_with_less_than_or_equal_to
1577
Topic.validates_numericality_of :approved, :less_than_or_equal_to => 10
1579
invalid!([11], 'must be less than or equal to 10')
1583
def test_validates_numericality_with_odd
1584
Topic.validates_numericality_of :approved, :odd => true
1586
invalid!([-2, 2], 'must be odd')
1590
def test_validates_numericality_with_even
1591
Topic.validates_numericality_of :approved, :even => true
1593
invalid!([-1, 1], 'must be even')
1597
def test_validates_numericality_with_greater_than_less_than_and_even
1598
Topic.validates_numericality_of :approved, :greater_than => 1, :less_than => 4, :even => true
1604
def test_validates_numericality_with_numeric_message
1605
Topic.validates_numericality_of :approved, :less_than => 4, :message => "smaller than {{count}}"
1606
topic = Topic.new("title" => "numeric test", "approved" => 10)
1608
assert !topic.valid?
1609
assert_equal "smaller than 4", topic.errors.on(:approved)
1611
Topic.validates_numericality_of :approved, :greater_than => 4, :message => "greater than {{count}}"
1612
topic = Topic.new("title" => "numeric test", "approved" => 1)
1614
assert !topic.valid?
1615
assert_equal "greater than 4", topic.errors.on(:approved)
1619
def invalid!(values, error=nil)
1620
with_each_topic_approved_value(values) do |topic, value|
1621
assert !topic.valid?, "#{value.inspect} not rejected as a number"
1622
assert topic.errors.on(:approved)
1623
assert_equal error, topic.errors.on(:approved) if error
1628
with_each_topic_approved_value(values) do |topic, value|
1629
assert topic.valid?, "#{value.inspect} not accepted as a number"
1633
def with_each_topic_approved_value(values)
1634
topic = Topic.new("title" => "numeric test", "content" => "whatever")
1635
values.each do |value|
1636
topic.approved = value