【问题标题】:Deleting models from database after Laravel Dusk tests have run?Laravel Dusk 测试运行后从数据库中删除模型?
【发布时间】:2017-06-23 09:30:39
【问题描述】:

我刚刚开始研究 Dusk - 我正在测试一些用户功能。

以下是我当前的测试,但是我正在尝试自己清理 - 例如,应该从数据库中删除新创建的用户。

我尝试使用tearDown 方法,但它似乎并没有真正删除它。

我通常会如何处理需要在之后进行垃圾处理的临时模型?

<?php

namespace Tests\Browser;

use App\User;
use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class LoginTest extends DuskTestCase
{

    protected $user = null;

    public function testIfPublicUsersLogin()
    {
        $this->user = $user = factory(User::class)->create([
            'is_student' => 0
        ]);

        $this->browse(function ($browser) use ($user) {

            $browser->visit('/login')
                ->assertVisible('#email')
                ->type('#email', $user->email)
                ->type('#password', 'secret')
                ->press('#loginButton')
                ->assertPathIs('/play');
        });
    }

    public function tearDown()
    {
        if ($this->user) {
            User::destroy($this->user->id);
            //$this->user->delete();
        }
    }
}

【问题讨论】:

    标签: php laravel phpunit laravel-dusk


    【解决方案1】:

    有多种方法可以实现这一点:

    1. 使用 DatabaseTransactions 特征,以便在每次测试后进行事务回滚。为此,请在您的 php 文件中添加:use Illuminate\Foundation\Testing\DatabaseTransactions;,并在您的测试类中添加 use DatabaseTransactions;
    2. 如果您想在每次测试之前和之后迁移和迁移回滚而不是将它们包装到事务中,您可能需要使用 DatabaseMigrations 特征。为此,请在您的 php 文件中添加:use Illuminate\Foundation\Testing\DatabaseMigrations;,并在您的测试类中添加 use DatabaseMigrations;
    3. 如果要使用自定义设置和拆卸方法,请使用 afterApplicationCreatedbeforeApplicationDestroyed 方法 而是注册回调

    【讨论】:

      【解决方案2】:
      <?php
      
      namespace Tests\Browser;
      
      use App\User;
      use Tests\DuskTestCase;
      use Illuminate\Foundation\Testing\DatabaseMigrations;
      
      class LoginTest extends DuskTestCase
      {
      
          protected $user = null;
      
          public function testIfPublicUsersLogin()
          {
              $this->user = $user = factory(User::class)->create([
                  'is_student' => 0
              ]);
      
              $this->browse(function ($browser) use ($user) {
      
                  $browser->visit('/login')
                      ->assertVisible('#email')
                      ->type('#email', $user->email)
                      ->type('#password', 'secret')
                      ->press('#loginButton')
                      ->assertPathIs('/play');
      
                  $user->delete();
              });
          }
      }
      

      此代码行$user-&gt;delete在测试后删除您的数据。 tearDown 方法没用。

      【讨论】:

        猜你喜欢
        • 2019-02-08
        • 2018-06-12
        • 2019-10-29
        • 2018-07-18
        • 2019-08-02
        • 2020-06-04
        • 2018-05-23
        • 1970-01-01
        • 2015-07-30
        相关资源
        最近更新 更多