by mbell · 3y ago · 0 comments
This is why I'm pretty dogmatic about variable comparison in tests.
This is dangerous and stuff like this has caused a lot bugs to slide though in my experience (and maybe ops):
expect(account1.balance).to eq account2.balance
This is safe and specifc: expect(account1.balance).to eq 2500
expect(account2.balance).to eq 2500
Unfortunately I've run into a lot of folks that take major issue with the later because of 'magic numbers' or some similar argument. In tests I want the values being checked to be be as specific as possible.There are too many yahoos out there writing impure functions or breaking pure ones that will mangle your fixture data. And the Sahara-DRY chuckleheads who see typing in 2500 twice (but somehow are okay with typing result.foo.bar.baz.omg.wtf.bbq twice) as some crime against humanity exacerbate things. Properly DAMP tests are stupid-simple to fix when the requirements change.
var expectedAccountBalance = 2500
expect(account1.balance).to eq expectedAccountBalance
expect(account1.balance).to eq account2.balanceI would advise you to try and convince your peers though and teach them the better way because I suspect that the people that you're fending off would not do what you did but rather just go w/ the one
expect(account1.balance).to eq account2.balance
Now while parts of the code base do the right thing (in a slightly long winded way), the rest of the code base written by these other people is still using bad tests.expect(account1.balance) eq 2500 before that isn't really a big problem.
Also "how to do it" is kinda different topic to "how to convince peers that's the right way"
Agreed on the ease of having problems of using variables on both sides.
Code that is write once read k < 10 times has very different lifecycle expectations than code that is constantly being work hardened.
The trick with the constants is that if they are declared and used in the same test scope, then the data is a black box. Nobody else 'sees' it, nobody interacts with it. The only time that's not true is when there's false sharing between unit tests and those tests are fundamentally broken. In that case the magic number is not the problem, it's the forcing function that makes you fix your broken shit.