Francois Beausoleil wrote:> Hello Sam,
>
> 2005/10/13, Sam Joseph <sam-wUweuJJ0J032eFz/2MeuCQ@public.gmane.org>:
>
>>Is there a way to display the message associated with validation
>>failure, or is that only an option from within a controller?
>
>
> You need the errors property of the model:
>
> u.errors.full_messages.inspect
>
> See
http://api.rubyonrails.com/classes/ActiveRecord/Validations.html#M000629
A while back (August 21 2005), in the thread "Reverse validation in
testing, no validation at all in development" Nicholas Seckar gave
advice on testing validation. Google can''t find this in on-line
archives
(and it''s not in the ASPN archive, even though other messages in the
same thread are there), so I''m reproducing the whole text below.
regards,
Justin
Nicholas Seckar (aka Ulysses) wrote:
Your validations ought to be tested in your unit tests (test/unit)
rather than functional tests.
Well, your functional tests should try to create and save invalid
objects too, but thinks work better if you first use your unit tests to
ensure that your validations work properly. Generally you''ll get better
errors, and it is an easier environment to debug models from.
If you find validation tests frustratingly verbose, check out my AR test
helper:
http://www.bigbold.com/snippets/posts/show/573
Using it, meanial tests such as
# Test to make sure the association tables are set up,
# and that the associated models can be loaded
def test_associations_work
assert project.users && project.users.find_all
assert project.owner
end
def test_validations_for_name
project.name = ''BigProject''
assert ! project.valid?
assert_matches /already taken/, project.errors.on(:name)
[nil, ''''].each dp |name|
project.name = name
assert ! project.valid?
assert_matches /can''t be blank/, project.errors.on(:name)
end
project.name = ''new name''
assert project.valid?
assert project.save # make sure the database agrees with us
end
Can be written as
check_associations %w(users owner)
check_validations_for :name do
invalid ''BigProject'', /already taken/
[nil, ''''].each {|name| invalid name, /can''t be
blank/}
valid ''new name''
end
Dry, eh? ;-) "