Using Selenium (or any other driver for that matter), I've never had to worry about whether the page has loaded or not, with one exception: if the page finishes loading, then loads more content via AJAX.
To handle this, you can use a spin function as documented in the Behat Manual.
http://docs.behat.org/en/v2.5/cookbook/using_spin_functions.html
The benefits of this are:
- It doesn't need you to use the selenium driver (for example, you could use PhantomJS if you want speed over looks).
- It won't break if you stop using jQuery and switch to something else (such as Angular's $httpProvider)
I wouldn't use theirs though, the back trace is broken and who want's to wait a second between checks anyway. :)
Try this:
Assuming you are using the Mink Context (thanks Mick), you can simply check the page every second or so until the desired
text has either appeared or dissapeared, or a given timeout has expired in which case we'd assume a fail.
/**
* @When I wait for :text to appear
* @Then I should see :text appear
* @param $text
* @throws \Exception
*/
public function iWaitForTextToAppear($text)
{
$this->spin(function(FeatureContext $context) use ($text) {
try {
$context->assertPageContainsText($text);
return true;
}
catch(ResponseTextException $e) {
// NOOP
}
return false;
});
}
/**
* @When I wait for :text to disappear
* @Then I should see :text disappear
* @param $text
* @throws \Exception
*/
public function iWaitForTextToDisappear($text)
{
$this->spin(function(FeatureContext $context) use ($text) {
try {
$context->assertPageContainsText($text);
}
catch(ResponseTextException $e) {
return true;
}
return false;
});
}
/**
* Based on Behat's own example
* @see http://docs.behat.org/en/v2.5/cookbook/using_spin_functions.html#adding-a-timeout
* @param $lambda
* @param int $wait
* @throws \Exception
*/
public function spin($lambda, $wait = 60)
{
$time = time();
$stopTime = $time + $wait;
while (time() < $stopTime)
{
try {
if ($lambda($this)) {
return;
}
} catch (\Exception $e) {
// do nothing
}
usleep(250000);
}
throw new \Exception("Spin function timed out after {$wait} seconds");
}