DEV Community

Discussion on: Fake data in tests

 
vasily profile image
Vasily Polovnyov

I see. I think, irrelevant data should not be at tests at all. That's why we use factories:
thoughtbot.com/blog/why-factories

Why? :) They don't say anything about the test

Oh, I'm sorry for the confusion. I put it there because it was actually used in test:

user = described_class.new(name: "Bart Simpson", email: "bart@simpson.dev")

expect(user.to).to eq "Bart Simpson <bart@simpson.dev>"
Enter fullscreen mode Exit fullscreen mode

What do you think?

Thread Thread
 
simeg profile image
Simon Egersand 🎈

I understand. Factories can be useful but the problem I see with them is that add additional logic to your test, and forces you to keep additional context in your head when you read the test. I try to avoid helper functions unless they are very obvious.

The example you provide is clear because the test is so small, but what if the user had 15 fields instead of 2?

Here's an interesting blog post on why you should avoid keeping logic in your tests.

Curious what you think!

Thread Thread
 
vasily profile image
Vasily Polovnyov

The example you provide is clear because the test is so small, but what if the user had 15 fields instead of 2?

It depends. If all these 15 fields are important to the test, I'll leave them as is. If not, I'll move them to some sort of helper or factory. See:
thoughtbot.com/blog/the-self-conta...

Here's an interesting blog post on why you should avoid keeping logic in your tests.

Awesome post. I agree completely with it: we should always optimize tests not for code brevity but for understanding.

Thread Thread
 
simeg profile image
Simon Egersand 🎈

It depends. If all these 15 fields are important to the test, I'll leave them as is. If not, I'll move them to some sort of helper or factory.

If you have 15 fields and you want to have tests for all of them, would that not leave you with a lot of factories?

You have convinced me factories are useful, but I'm still scared of abusing them. I need to experiment more to understand the trade-offs and learn how to balance.

[..] we should always optimize tests not for code brevity but for understanding.

Could not agree more!

How to write helpful, understandable and maintainable tests are often overlooked, in my opinion, and I really enjoy learning more about it. Far too many times I've had to spend many brain cycles just to understand what a test is actually verifying.

If you have more test related blog posts to share, please send them my way, friend!