assert with == is evil

Posted by admin, Wed Mar 21 09:34:59 UTC 2007

It’s time for a rant. I am so tired of seeing badly written unit tests used as examples that I could just scream. If I never see another example like:

  assert flash[:notice] == "Please log in" 

I would be happy. But I see it all the time, and my teeth need a break from all the grinding, so let’s see if I can shed some light on why this is not a good unit test.

No doubt, some of you are innocently wondering… what’s wrong with that? Well, let me tell you what’s wrong with it. If that test fails, what exactly does it tell you? NOTHING, except that it failed. You will have absolutely no idea WHY your stupid assert failed. < “true”> expected but was < “false”>. That’s SO useful, isn’t it? You’ll know exactly what happened and where to go and fix it won’t you? No, you won’t. Now you’ll have to go in and annotate your test and drop in a “puts” to see what the flash actually contains. Then you’ll have to run the test again, and then you might be able to go and fix it. What a complete waste of time!

So why would you not write this, equivalent, assert instead?

  assert_equal "Please log in", flash[:notice]

Now, what happens when this assert fails? You get nice, USEFUL feedback like – < “Please log in”> expected but was < “Login successful”>. You won’t have to go and change your test. You won’t have to rerun your test. You will have a very good idea of exactly where to go and look for your problem. And you will save a lot of time.

So, go forth and rewrite all your assert … == unit tests to use assert_equals instead.

Filed Under: | Tags:

Comments

  1. Colour-blind guy 04.15.07 / 05AM
    I hope I didn't write that one! :)
  2. lori 04.17.07 / 04AM
    Nope. I was reading an example on someone's blog.

Have your say

A name is required. You may use HTML in your comments.