2015-03-13 57 views
0

我正在使用Behat 3和Mink爲Laravel 5應用程序進行我的第一次驗收測試。Behat 3與Laravel 5:驗收測試通過但不應該

該應用程序在Homestead VM下運行。

測試很簡單,位於features/example.feature文件中。這是測試:

Feature: Sample 

    In order to learn Behat 
    As a programmer 
    I need a simple url testing 

    Scenario: Registration 
     Given I am not logged in 
     When I go to the registration form 
     Then I will be automatically logged in 

FeatureContext.php有這個類:

<?php 

use Behat\Behat\Tester\Exception\PendingException; 
use Behat\Behat\Context\Context; 
use Behat\Behat\Context\SnippetAcceptingContext; 
use Behat\Gherkin\Node\PyStringNode; 
use Behat\Gherkin\Node\TableNode; 
use Behat\MinkExtension\Context\MinkContext; 

/** 
* Defines application features from the specific context. 
*/ 
class FeatureContext extends MinkContext implements Context, SnippetAcceptingContext 
{ 
    /** 
    * Initializes context. 
    * 
    * Every scenario gets its own context instance. 
    * You can also pass arbitrary arguments to the 
    * context constructor through behat.yml. 
    */ 
    public function __construct() 
    { 
    } 

    /** 
    * @Given I am not logged in 
    */ 
    public function iAmNotLoggedIn() 
    { 
     Auth::guest(); 
    } 

    /** 
    * @When I go to the registration form 
    */ 
    public function iGoToTheRegistrationForm() 
    { 
     $this->visit(url('my/url')); 
    } 

    /** 
    * @Then I will be automatically logged in 
    */ 
    public function iWillBeAutomaticallyLoggedIn() 
    { 
     Auth::check(); 
    } 
} 

然後,當我在命令行中運行behat,我希望測試失敗,因爲沒有my/url路由( routes.php文件只有路線/)。

然而,測試返回綠色,這是我所看到的:

Feature: Sample 

    In order to learn Behat 
    As a programmer 
    I need a simple url testing 

    Scenario: Registration     # features/example.feature:7 
    Given I am not logged in    # FeatureContext::iAmNotLoggedIn() 
    When I go to the registration form  # FeatureContext::iGoToTheRegistrationForm() 
    Then I will be automatically logged in # FeatureContext::iWillBeAutomaticallyLoggedIn() 

1 scenario (1 passed) 
3 steps (3 passed) 
0m0.45s (22.82Mb) 

當然,我使用的是laracasts/behat-laravel-extension包,這是beat.yml文件的內容:

default: 
    extensions: 
     Laracasts\Behat: ~ 
     Behat\MinkExtension: 
      default_session: laravel 
      laravel: ~ 

非常感謝您的幫助!

回答

1

Behat很簡單。如果在執行過程中拋出異常,它會將步驟視爲失敗。它會將一個步驟視爲成功,否則。

據我所知,從the docsAuth::check()不引發異常,如果用戶未經過身份驗證。它只是返回一個布爾值。

你的第一步應該是相當實施了類似如下:

/** 
    * @Then I will be automatically logged in 
    */ 
    public function iWillBeAutomaticallyLoggedIn() 
    { 
     if (!Auth::check()) { 
      throw new \LogicException('User was not logged in'); 
     } 
    } 

「我去報名登記表」步驟成功,因爲你真的不驗證,如果您訪問的頁面是一個你期望加載。同樣,如果您訪問的頁面不正確,您應該拋出異常。

+0

我同意'Auth :: check()',沒有發生異常,所以Behat不會失敗。我在'iGoToTheRegistrationForm()'方法中遇到了麻煩,因爲當我訪問'my/url'頁面時,Laravel實際上會拋出一個異常,因爲該頁面不存在 – 2015-03-13 15:33:54

+0

Laravel可能會拋出一個異常,但這會導致錯誤頁面正在呈現。步驟不會引發異常。 – 2015-03-13 23:16:19

+0

換句話說,您仍然需要確保您實際訪問的頁面不是錯誤頁面。 – 2015-03-15 12:37:27