MDL-40315 behat: Performance improvement

We look for exceptions after each step, this patch
includes a pre-checking query to avoid multiple queries
for each step when most of the time they are not necessary.