The Rails core team have really been kicking out some cool stuff recently. One addition I’ve been taking full advantage of is the assert_differnce() method (changeset here). This method is only available to those of you who are using Edge Rails.
If you need to test something that changes, then assert_differnce() is perfect. Below is a typical example of something changing. We have a user class and we want to test the destroy method to make sure the user really does get destroyed.
Let’s take a step back for a moment. What changes when this user is deleted? User.count does, because there is now one less user to count. So we need to ensure that there is a difference in the count of users after deleting a user.
Before
class UserTest < Test::Unit::TestCase
fixtures :users
def test_should_delete_first_user
# Record current user count
old_count = User.count
# Delete the first user we find
User.find(:first).destroy
# Make sure the count is now 1 less than it was before
assert_equal old_count -1, User.count
end
end
After (using assert_difference)
class UserTest < Test::Unit::TestCase
fixtures :users
def test_should_delete_first_user
assert_difference('User.count', -1) do
User.find(:first).destroy
end
end
end
Ah yes, much nicer.
But don’t you have to be careful that the difference is what you expected it to be? i.e. deleting a user shouldn’t increase the count … so the first test may look awkward, but protects you from this misunderstanding?