In my last post, about test automation, I wrote about using sleep : “Bad, bad, bad. Don’t do this.” But why not? Well, the way I was doing it there — until d.exists? — really wasn’t that horrible. What you really want to stay away from, and what I’ve seen people start out with, is sleep with a hard-coded time value. “But I know the app’s going to take a few seconds to be ready,” they say, “so I just put in a 5-second delay.”
Let’s look at — in human terms — what we’re talking about. Imagine for a moment that your extremely strict boss wants to know what colour taxi he’ll be taking to the airport, and sends you outside to look.
He knows the car’s due to arrive in the next five minutes, so his instruction is a simple one: “Go outside and wait five minutes with your eyes closed. At the end of that time, open your eyes. Look at the car at the curb and come tell me what colour it is.”
Can you see any problems with that task? I see two right away. First, it’s potentially a waste of your time and his. What are you to do if the taxi arrives before the five-minute mark? Nothing. He expressly told you to wait five minutes, then look at the car. If the driver’s having a good day and shows up early, too bad. You wait uselessly at the curb; he waits impatiently for an answer that you could have delivered earlier.
Secondly, he gave you no instructions on what to do if traffic is bad and the taxi isn’t there on time. You’ll have to go back and deliver a non-answer. Next time, he may decide that five minutes wasn’t enough, so he’ll try giving you a ten-minute wait time.
This is decidedly non-optimal.
“But wait,” you say to your manager, “Why don’t I just wait until I see a taxi, then come and let you know.” That is what you’d say, right? Of course it is. That’s exactly what we want our computers to say, too.
That’s the purpose of until. Give the computer a specific condition, and the flexibility to wait just long enough until that condition becomes true. In my previous Ruby/Watir example, we waited until an element existed, or until one contained a particular text string. Other language/testing frameworks have similar syntax. Using WebDriver, for example, you’d use wait.Until()
Until our computers get a bit more intelligent and understand what we mean rather than what we say (and given the potential state of computer intelligence maybe that’s not a good idea), we need to be explicit in our instructions while making those instructions flexible enough to work well in the real world.