Laravel 5 使用工厂测试Laravel post请求
我正在为我的Laravel应用程序编写一些功能测试。我是TDD的新手,所以这对一些人来说可能是显而易见的 LocationsFactory.phpLaravel 5 使用工厂测试Laravel post请求,laravel-5,tdd,Laravel 5,Tdd,我正在为我的Laravel应用程序编写一些功能测试。我是TDD的新手,所以这对一些人来说可能是显而易见的 LocationsFactory.php use Faker\Generator as Faker; $factory->define(App\Location::class, function (Faker $faker) { return [ 'name' => $faker->name, ]; }); public function
use Faker\Generator as Faker;
$factory->define(App\Location::class, function (Faker $faker) {
return [
'name' => $faker->name,
];
});
public function a_user_can_create_a_location(): void
{
$this->withExceptionHandling();
$user = factory(User::class)->make();
$location = factory(Location::class)->make();
$response = $this->actingAs($user)->post('/locations', $location); // $location needs to be an array
$response->assertStatus(200);
$this->assertDatabaseHas('locations', ['name' => $location->name]);
}
LocationsTest.php
use Faker\Generator as Faker;
$factory->define(App\Location::class, function (Faker $faker) {
return [
'name' => $faker->name,
];
});
public function a_user_can_create_a_location(): void
{
$this->withExceptionHandling();
$user = factory(User::class)->make();
$location = factory(Location::class)->make();
$response = $this->actingAs($user)->post('/locations', $location); // $location needs to be an array
$response->assertStatus(200);
$this->assertDatabaseHas('locations', ['name' => $location->name]);
}
TypeError:传递给Illumb\Foundation\Testing\TestCase::post()的参数2必须是给定对象的数组类型
我知道错误告诉我,$location
需要是一个数组,它是一个对象。然而,因为我使用的是工厂,所以它是作为一个对象出现的。在我的测试中使用工厂有更好的方法吗
这似乎也有点不对劲:
$this->assertDatabaseHas('locations', ['name' => $location->name]);
因为我使用的是faker,所以我不知道名称是什么。所以我只是检查生成的东西,这是理想的吗
谢谢你的建议
编辑
这样做很好(也许这就是解决方案)
但是,假设我的位置有30个属性。看起来很快就会变丑。Laravel 5
使用toArray()
$user=factory(user::class)->make();
$location=factory(location::class)->make();
$response=$this->actingAs($user)->post('/locations',$location->toArray());
$response->assertStatus(200);
$this->assertDatabaseHas('locations',['name'=>$location->name]);
您还可以使用raw
将属性构建为一个数组
$user = factory(User::class)->make();
$location = factory(Location::class)->raw();
$response = $this->actingAs($user)->post('/locations', $location);
$response->assertStatus(200);
$this->assertDatabaseHas('locations', $location);
我以为我已经试过了,但显然没有正确地实施。非常感谢你!