Joshua Muheim wrote:
> I'm trying to write good unit tests. Here's part of my blog_test.rb:
>
> --- blog_test.rb:
>
> require File.dirname(__FILE__) + '/../test_helper'
>
> class BlogTest < Test::Unit::TestCase
> fixtures :blogs,
> :comments
>
> def setup
> @valid_blog = Blog.new(valid_blog_attributes)
Don't construct a blog - fetch one from the fixtures:
@valid_blog = blogs(:valid_blog)
> end
>
> def test_should_be_able_to_have_many_comments
> @valid_blog.comments = {}
> assert_valid @valid_blog
The assertion that the blog is valid should be in the setup or another test.
Each test case should only speak to one activity.
> comments.each do |comment|
Where does comments come from? you are probably picking up comments(), which is
the fixture loader. It returns an array unless you pass one comment, so you are
now slipping off that array. Try this:
comments(:first_comment, :second_comment).each do |comment|
> @valid_blog.comments << comment
> assert_not_nil @valid_blog.comments
As you get better at testing, you will get bored with testing that ActiveRecord
behaves as advertised, and you will test your actual logic.
To set a good example here, don't test against nil, because if comments were an
empty array, then assert_not_nil [] would pass.
Instead, test that the comment went in:
assert{ @valid_blog.comments.last == comment }
That illustrates two things. It shows my assert{ 2.0 }, which turns any
expression into a generic assertion, and it shows AR evaluates == as true if
two
records have the same ID.
assert{ @valid_blog.valid? }
> end
> end
> end
>
> --- comments.yml:
>
> first_comment:
> id: 1
> subject: "Dies ist der erste Kommentar"
> body: "Dies ist der Inhalt des ersten Kommentars"
If you use Rails >2, don't use the id: 1. Let the fixturizer build the number
for you. This makes coding much simpler.
Next, don't call it first_comment. Name it after the theme of your comment.
--
Phlip
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---