DEV Community

Leandro Gomes
Leandro Gomes

Posted on

Should I test initialize?

So, yesterday I was discussing with my team if it is a waste of time to test initialize method in ruby using rspec.

Usually, when we test a method which needs to instantiate a class (.new), initialize method is implicitly tested. But we only "implicit test" private methods and initialize is a public method.

Another point is that initialize should only create attributes without complex logic.

What do you think about that?

Top comments (4)

Collapse
 
ben profile image
Ben Halpern

only create attributes without complex logic

This is probably not a good enough point to avoid testing it. The method is still part of something complex and the tests help ensure the acceptability of the code as a whole.

However, yes it is implicitly tested most of the time. If you hold that pattern to be true throughout the app, than you probably don't need to test it. But that hardly seems like a universal truth. I could think of times you'd just call Object.new, perhaps to pass into a form_for.

It seems like part of the reason we typically don't test private methods is that it's sort of inconvenient and perhaps messy to do so. And for that reason, we can settle on testing them implicitly. Testing Object.new seems a lot more straightforward.

We do not test Object.new but in writing this, I feel like we should. But I'd love to hear my points debated or anyone else's thoughts on the issue.

Collapse
 
leandrogs profile image
Leandro Gomes • Edited

The method is still part of something complex and the tests help ensure the acceptability of the code as a whole.

I could think of times you'd just call Object.new, perhaps to pass into a form_for.

Those are the points I trust in. Even if it is implicitly tested, it still is a public method.

Collapse
 
databasesponge profile image
MetaDave πŸ‡ͺπŸ‡Ί

I would definitely highlight the issue of complex initialisers being questionable. The purpose of the initialiser is surely to set instance variables, and I would see anything else that it does as a code smell.

That reduces the initialiser to setting instance variables, and the values of those instance variables may not by themselves be publicly available.

Furthermore, if you test an initialiser it seems to me that you should be testing an interface between your class and the rest of the code base, and it is generally that interfacing action that should be the subject of the test.