Unit Tests: Don’t You Forget About Me

Image result for breakfast club closing

I have an appreciation for FactoryGirl and its syntactic sugar. Having said that, I dislike how easy it is to create entire object graphs.

Yes. That statement even feels weird to me as a write it. I dislike how easy something is. Bear with me.

Write unit tests first. Not integration tests. When setting up mocks and dependencies in your unit tests becomes a pain in the ass, that is your code signaling for a refactor. And that is the true power of TDD.

FactoryGirl is beautiful when writing integration tests. It’s syntactically sweet and simple. Features like traits provide a clean way to DRY up test arrangement while still conveying intent. Yet, because it’s incredibly easy to create the entire object graph, it’s easy to lose sight of how much of the object graph your code is dependent upon. And then it becomes easy to violate Law of Demeter. Unless your team is vigilant about preventing LOD violations, this can bite you.

This is why I love unit tests. The value of TDD goes beyond quality and regression protection; it also drives architecture. But when we only write integration tests, we start to lose sight of our boundaries. When it’s so easy to reach across boundaries, we forget they exist. Write unit tests first. Not integration tests. When setting up mocks and dependencies in your unit tests becomes a pain in the ass, that is your code signaling for a refactor. And that is the true power of TDD.

Don’t get me wrong. FactoryGirl is a solid implementation of the factory pattern. But if you write unit tests first, and then use FactoryGirl for integration tests, you’ll start to see the payoff.


Your Thoughts?

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s