mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Tests and docs which explain the use of validate with a block and without arguments
This commit is contained in:
parent
08ccd29b5b
commit
5fb42ac478
2 changed files with 20 additions and 2 deletions
|
@ -104,7 +104,7 @@ module ActiveModel
|
|||
# end
|
||||
# end
|
||||
#
|
||||
# Or with a block which is passed with the current record to be validated:
|
||||
# With a block which is passed with the current record to be validated:
|
||||
#
|
||||
# class Comment
|
||||
# include ActiveModel::Validations
|
||||
|
@ -118,6 +118,16 @@ module ActiveModel
|
|||
# end
|
||||
# end
|
||||
#
|
||||
# Or with a block where self points to the current record to be validated:
|
||||
#
|
||||
# class Comment
|
||||
# include ActiveModel::Validations
|
||||
#
|
||||
# validate do
|
||||
# errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
|
||||
# end
|
||||
# end
|
||||
#
|
||||
def validate(*args, &block)
|
||||
options = args.extract_options!
|
||||
if options.key?(:on)
|
||||
|
|
|
@ -148,6 +148,14 @@ class ValidationsTest < ActiveModel::TestCase
|
|||
end
|
||||
|
||||
def test_validate_block
|
||||
Topic.validate { errors.add("title", "will never be valid") }
|
||||
t = Topic.new("title" => "Title", "content" => "whatever")
|
||||
assert t.invalid?
|
||||
assert t.errors[:title].any?
|
||||
assert_equal ["will never be valid"], t.errors["title"]
|
||||
end
|
||||
|
||||
def test_validate_block_with_params
|
||||
Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
|
||||
t = Topic.new("title" => "Title", "content" => "whatever")
|
||||
assert t.invalid?
|
||||
|
@ -187,7 +195,7 @@ class ValidationsTest < ActiveModel::TestCase
|
|||
assert t.invalid?
|
||||
assert_equal "can't be blank", t.errors["title"].first
|
||||
Topic.validates_presence_of :title, :author_name
|
||||
Topic.validate {|topic| topic.errors.add('author_email_address', 'will never be valid')}
|
||||
Topic.validate {errors.add('author_email_address', 'will never be valid')}
|
||||
Topic.validates_length_of :title, :content, :minimum => 2
|
||||
|
||||
t = Topic.new :title => ''
|
||||
|
|
Loading…
Reference in a new issue