Be careful with assert_not_equal

As I discovered today, assert_not_equal has a pretty big problem: it does exactly what you ask it to do.

I just need to make sure that a user has at least one record:

assert_not_equal 0, UserPreference.find_by_user_id(user_id)

As you may have just caught: that is always going to pass. Not a tough mistake when you’re motoring along and not putting too much thought into something so simple: The finder isn’t going to return the count of matching rows… it’s either going to return a populated object or nil, neither of which will be equal to 0.

Fixing the bug is trivial, but lesson learned:

From now on whenever I write assert_not_equal – I am going to make sure it works by temporarily changing it to assert_equal and taking a look at the error message.

In this case: if the error message said something like “<0> expected but was <2>”, I would know that things are working.

Whereas if the error said “<0> expected but was <#<UserPreference…>>”, I’d know right away that I need to fix it up (and have one more cup of coffee).

Advertisements

2 Comments

Filed under rails, Ruby, Test Driven Development (TDD)

2 responses to “Be careful with assert_not_equal

  1. This is one reason why I think its better to use a more specific assertion. For making sure a collection isn’t empty, for example:
    assert_false User.find_some_stuff(x, y).empty?

    or even:

    assert User.find_some_stuff(x,y).size > 0

  2. assert_not_equal by itself is almost evil.

    They should have assert_greater_than (or greater than or equal to, …) functions as well, or not have assert_not_equal at all (thereby forcing you to use plain old assert), in which you’d use a greater than sign.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s