【发布时间】:2017-09-03 17:25:09
【问题描述】:
我正在尝试在我的应用中添加个人资料图片功能。我正在使用 TDD 方法来执行此操作。上传头像测试显示绿色。但是当我运行测试以更新个人资料图片时,它会出错。下面是代码:
控制器:
public function store(StoreAvatarRequest $request)
{
$path = $request->file('avatar')->store('avatars');
BasicInformation::updateOrCreate([
'user_id' => auth()->id(),
], [
'user_id' => auth()->id(),
'avatar' => $path,
]);
$this->showAlerts('alert-success', 'Profile Image uploaded successfully');
return redirect()->route('avatar.index');
}
public function update(StoreAvatarRequest $request, $id)
{
$basicProfile = BasicInformation::find($id)->first();
$oldAvatarPath = $basicProfile->avatar;
if ($basicProfile->user_id == auth()->id()) {
$path = $request->file('avatar')->store('avatars');
$basicProfile->avatar = $path;
$basicProfile->update();
Storage::delete($oldAvatarPath);
$this->showAlerts('alert-success', 'Profile Image Updated Successfully');
return redirect()->route('avatar.index');
} else {
// TODO :: Need to add logic here
}
}
测试用例:
public function can_update_profile_picture()
{
$this->actingAs($this->lawyer)->post(route('avatar.store'), [
'avatar' => UploadedFile::fake()->image('avatar.jpg', 600, 600)
]);
$oldImagePath = $this->lawyer->information->avatar;
$this->actingAs($this->lawyer)->put(route('avatar.update', ['id' => $this->lawyer->information->id]), [
'avatar' => UploadedFile::fake()->image('avatar1.jpg', 600, 600)
])
->assertRedirect(route('avatar.index'))
->assertSessionHas('status', 'Profile Image Updated Successfully');
Storage::disk('local')->assertExists($this->lawyer->information->avatar);
Storage::disk('local')->assertMissing($oldImagePath);
}
我在运行测试时收到以下错误:
PHPUnit 5.7.19 by Sebastian Bergmann and contributors.
F 1 /
1 (100%)
Time: 298 ms, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\Dashboard\Lawyer\Account\ProfileImageTest::can_update_profile_picture
Unable to find a file at path [local/c5tjUUQDzU4iKHauJK68Z801I5iaYJ7e3cVQ5iA1.jpeg].
Failed asserting that false is true.
【问题讨论】:
-
我认为你的旧头像应该是
$oldImagePath = $this->lawyer->avatar而不是$this->lawyer->information->avatar -
@AmrAly 那是调试错字。我已经纠正了。但我得到了同样的错误。同样对于两个断言(assertMissing 和 assertExists),我都收到了错误消息。 "无法在路径中找到文件",
-
也是在BasicInformation Model中定义的头像列和与User Model的hasOne关系。所以我使用 $this->lawyer->information->avatar 来引用 $oldImagePath
-
您是否尝试过使用文件名,例如
assertExists('avatar1.jpg');和assertMissing('avatar.jpg');