php - Laravel - phpunit 更新方法失败,我不知道为什么
问题描述
这是我第一次编写测试,所以我为更新方法写了一个,我不知道我做错了什么,如果有更好的测试方法请告诉我,提前谢谢
路线
Route::group(['prefix' => 'categories' , 'namespace' => 'App\Http\Controllers\Admin'] , function () {
Route::post('create', 'CategoryController@store')->name('category.store');
Route::put('update/{category}', 'CategoryController@update')->name('category.update');
});
这是我的控制器
控制器
public function update(Request $request , Category $category)
{
$category->update($request->all());
}
测试
/** @test */
public function a_category_can_be_updated()
{
$this->withoutExceptionHandling();
$this->post(
route('category.store'),
[
'name' => 'Food',
'slug' => 'food-and-drinks',
],
);
$category = Category::first();
$this->put(
route('category.update', $category->id),
[
'name' => 'Food and',
],
);
// dd($category);
$this->assertEquals('Food and', $category->name);
$this->assertEquals('Food-and', $category->slug);
}
错误来自测试
• Tests\Feature\CategoriesTest > a category can be updated
Failed asserting that two strings are equal.
at F:\newProject\tests\Feature\CategoriesTest.php:66
62▕ ],
63▕ );
64▕ // dd($category);
65▕
➜ 66▕ $this->assertEquals('Food and', $category->name);
67▕ $this->assertEquals('Food-and', $category->slug);
68▕ }
69▕ }
70▕
1 F:\newProject\vendor\phpunit\phpunit\phpunit:61
PHPUnit\TextUI\Command::main()
--- Expected
+++ Actual
@@ @@
-'Food and'
+'Food'
模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class Category extends Model
{
protected $table = 'categories';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('name', 'slug', 'parent_id');
public function posts()
{
return $this->belongsToMany('App\Models\Post');
}
//slugging the Category-name
public function setSlugAttribute($value)
{
$this->attributes['slug'] = Str::slug($this->attributes['name']);
}
public function scopeParent()
{
return Category::whereNull('parent_id');
}
}
让我知道代码发生了什么,在此先感谢
解决方案
如“IGP”所述,您必须$category->fresh()
在执行更新后使用。但是将其分配给您$category
,如下所示:$category = $category->fresh();
查看 Laravel 文档了解详细信息:Eloquent ORM Refreshing Models
推荐阅读
- python - 为什么 Pandas DataFrame 函数 'isin()' 需要这么长时间?
- python - 如何在 BeautifulSoup 中检索部分 html 标签?
- python - 在 Python 中创建一个非常大的缺席/存在 SPARSEE 矩阵
- javascript - 使用 setCustomValidity 进行电子邮件验证
- servlets - Apache Camel - HTTP 404 而不是 405
- python - [Python - Pandas]:将一个数据帧中的所有数据复制到另一个日期帧上的每一行
- ios - Xamarin iOS 选项卡栏更多停止所有导航工作
- java - 将 ENUM 值存储到数据库中
- python - OpenCV 视频只显示单帧而不是连续帧
- encoding - 为什么“仅”使用 Base64 来编码二进制数据?