Alex Moore wrote:> I''m having a bit of difficulty when testing my models,
I''ve read a few
> times the testing chapter in Agile web development with rails and at
> http://manuals.rubyonrails.com/read/chapter/27 but i''m still
unsure of
> what I should be testing.
>
> Firstly I''d like to be able to test things like my email
validation
> using lines such as
>
> assert User.new(:email =>
''test@test.com'').errors.on(:email)
>
> but this just returns nil for both a valid and an invalid email address.
>
> To what extent should i do my unit tests, do i go through and confirm
> all the important validations?
>
> Any suggested reading would be greatly appreciated.
Tests should be created for ANY code which you write. Simple as that.
Test associations, validations, and all methods. And to really do it
right, write the test first, make sure it fails, then write the code to
make the test pass.
If you want to add a new validation, create a test that makes sure the
validation works first, then run the tests. Make sure it fails. If it
passes your test is bad. Now implement your new validation and be sure
your test passes. This ensures that your test is actually testing what
it''s supposed to be testing and it assures that the change you just
made
is what makes the test pass.
Now to address your specific case. I would do something like this:
def test_validation
user = User.new(:email => ''bunk-email-addy'')
assert !user.save
assert user.errors.invalid?(:email)
user.email = ''goodemail@example.com''
assert user.save
end
Alternatively, you can use an assert_valid and assert_invalid custom
assertions that I picked off someones blog a while back. It makes it
super easy to test the validity, and more importantly, the invalidity
against a slew of bad values.
assert_valid some_object
assert_invalid some_object, :some_field, nil, '''',
''bad1'', ''bad2''
assert_invalid will check that the object cant be saved and that
:some_field is the one with the error on it. It will do this for each
of the values passed to it ensuring each one is invalid.
Get the code for those assertions and an example test here.
http://pastie.caboo.se/8801
--
Posted via http://www.ruby-forum.com/.