2016-11-25 44 views

回答

2

您應該使用css定期查找標題標記並使用getText()來獲取標題。

CSS的應該是:「頭題」

您的解決方案几乎是好的,你需要注意的可能是個例外,尤其是致命的,如果遇到可以阻止您的套房。

例如find()方法會返回一個對象或null,如果返回null和你在予以使用getText()它會導致致命異常和您的套房將停止。

略有改善方法:

/** 
* @Given /^the page title should be "([^"]*)"$/ 
*/ 
public function thePageTitleShouldBe($expectedTitle) 
{ 
    $titleElement = $this->getSession()->getPage()->find('css', 'head title'); 
    if ($titleElement === null) { 
     throw new Exception('Page title element was not found!'); 
    } else { 
     $title = $titleElement->getText(); 
     if ($expectedTitle !== $title) { 
      throw new Exception("Incorrect title! Expected:$expectedTitle | Actual:$title "); 
     } 
    } 
} 

改進:

  • 處理可能致命異常
  • 拋出異常,如果沒有找到元素
  • 拋出異常與細節,如果標題不匹配

請注意,您也可以使用其他方法來檢查標題,如:striposstrpos或簡單地比較字符串,就像我一樣。我更喜歡簡單的比較,如果我需要確切的文本或strpos/stripos方法的個人,避免定期異常和像preg_match相關的方法,通常會慢一點。

你可以做的一個主要改進是有一個等待元素併爲你處理異常的方法,並用它來代替簡單的查找,當你需要根據元素的存在性來決定時,可以使用它像︰如果存在的元素做這個別的..

0

謝謝勞達。是的,這確實有效。寫下以下功能:

/** 
    * @Given /^the page title should be "([^"]*)"$/ 
    */ 
    public function thePageTitleShouldBe($arg1) 
    { 
     $actTitle = $this->getSession()->getPage()->find('css','head title')->getText(); 
     if (!preg_match($arg1, $actTitle)) { 
      throw new Exception ('Incorrect title'); 
     } 
    } 
相關問題