Sunday, June 22, 2008

Rails Validations & Unit Tests

I was doing a new feature in an existing rails project, and after finishing that feature, i ran all tests to check that everything is fine and no failures or errors occurred after my change

i ran the tests and found a failure in one of the unit tests, i opened it to see what is the problem. at this point i found in that file a function that gained my attention.

before stating what is inside this function, lets have a look at the part of the model that is being tested by this function

class Feed < ActiveRecord::Base
validates_presence_of :name


we can see in this part that name field should be present for the model to be valid, now lets look at the testing function

f =
assert !f.valid?
assert f.errors.invalid?(:action)

So, what is the point in this code? the point is that at my first look at this function, i considered it a redundant test function because it checks an already tested rails function which is the validation function.

so i asked a friend of mine about his opinion, and he agreed with me that it is redundant and useless

later on, i asked someone with greater experience about his opinion also in this function as it represents a class of functions found in many models checking such validations.

But his opinion was different. he considered it useful and justified that by stating that this function tests the contract (which is that no feed is accepted if no name is stated) with the client, so that if someone later on changed this part in a wrong way, this test will alert us that the contract has changed. so that we reconsider our action to see if it has been really changed by the contract or by mistake

i found that answer reasonable and added to me a new way of thinking towards tests which is testing the agreements rather than checking whether our code is working or not

No comments: