【发布时间】:2020-03-05 10:58:37
【问题描述】:
升级到 laravel 5.8 / PHPUnit 8 后,我有几个测试开始失败。例如下面的测试。
public function testAdminCanPromoteUsers()
{
// While using a admin account try to promote non-admin user
$this->actingAs($this->admin)
->post('user/promote', ['userPromoteId' => $this->user->id, 'name' => $this->user->name]);
// check if user was promoted to admin
$user = User::find($this->user->id);
$this->assertTrue((bool) $user->isAdmin);
}
路线
| POST | user/allow | App\Http\Controllers\UserController@allow | web,admin|
| POST | user/demote | App\Http\Controllers\UserController@demote | web,admin|
| POST | user/promote | App\Http\Controllers\UserController@promote | web,admin|
| POST | user/reset | App\Http\Controllers\UserController@reset | web,admin|
| POST | user/restrict | App\Http\Controllers\UserController@restrict | web,admin|
用户模型
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Auth;
class User extends Authenticatable
{
use Notifiable;
public static $snakeAttributes = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
用户迁移
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email', 191)->unique();
$table->string('password');
$table->boolean('isAdmin')->default(false);
$table->boolean('hasAccess')->default(true);
$table->rememberToken();
$table->timestamps();
});
}
用户控制器功能
/**
* Make an user as admin
*/
public function promote(Request $request) {
// Create the collection name
$thisUsr = User::findOrFail($request->userPromoteId);
if (strcasecmp($thisUsr->name, $request->name) == 0) {
$thisUsr->isAdmin = true;
$thisUsr->save();
return redirect()->route('userIndex');
}
// Error message
return redirect()->route('userIndex')->withErrors("Failed to Promote User to Admin. User wasn't found.");
}
PHPUnit 结果
1) UserControllerTest::testAdminCanPromoteUsers
断言 false 为 true 失败。/var/www/tests/Feature/Controllers/UserControllerTest.php:61
浏览器中的一切仍然正常,只是测试失败了。任何可能导致失败的改变的想法。
【问题讨论】:
-
你能发布整个用户模型吗?
-
完成更新问题。
-
$user->isAdmin是一个字段吗?$this->user是否在测试中持久化到数据库? -
是的,这是正确的
-
isAdmin是什么字段?