SCENARIO:
I am running a Post test on my api, as a 'User':
./vendor/bin/phpunit
and the following is returned in the terminal:
There was 1 error:
1) Tests\Feature\PostTest::testStoreValid
ErrorException: Undefined property: Tests\Feature\PostTest::${"name":"Elfrieda Hoppe","email":"[email protected]","email_verified_at":"2022-08-15T05:24:00.000000Z","updated_at":"2022-08-15T05:24:00.000000Z","created_at":"2022-08-15T05:24:00.000000Z","id":1}
*Here is my TestCase.php:
<?php namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use App\Models\User;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function user()
{
return User::factory()->create();
}
}
*Here is my PostTest.php:
<?php namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PostTest extends TestCase
{
use RefreshDatabase;
public function testStoreValid()
{
$user = $this->user();
$params = [
"title" => "Valid Title",
"content" => "At least 10 characters",
];
$this->actingAs($this->$user)
->post("/posts", $params)
->assertStatus(302)
->assertSessionHas("status");
$this->assertEquals(session("status"), "the blog post was created!");
}
}
*Here is my User.php:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $fillable = ["name", "email", "password"];
protected $hidden = ["password", "remember_token"];
protected $casts = [
"email_verified_at" => "datetime",
];
}
*And here is my UserFactory.php:
<?php namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
"name" => $this->faker->name,
"email" => $this->faker->unique()->safeEmail,
"email_verified_at" => now(),
"password" =>
'$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
"remember_token" => Str::random(10),
];
}
}
-Apparently the model is being successfully created with "fake" data, however, php unit recognizes the object that is returned from my model as an undefined property. What is the meaning of this?
-Thank you for your time!
CodePudding user response:
The problem is the line:
$this->actingAs($this->$user)
It should be:
$this->actingAs($this->user)
You have a extra $
in front of the user, so it thinks you are passing a variable.
CodePudding user response:
Thank you for your input, everyone! This one worked -as suggested by, Bhola Kr. Khawas:
$this->actingAs($user)
Originally I was put off from doing this because, there is a squiggly line that suggests something is wrong. But it appears to work anyway:
--Would anyone be able to elucidate the squiggly line under $user
?