I am following a tutorial PluralSight by Stephen Macguire "Play by Play: Getting Started with Laravel 5", the code for which is on GitHub http://ift.tt/2gITLk5.
(However, the code below is slightly different from the code on GitHub. The code on Git Hub has the line in the test:
$this->post(route('api.products.store'), $product->jsonSerialize(), $this->jsonHeaders)
In my test the code has the line:
$this->post(route('api.products.store'), $product->jsonSerialize())
My other tests post without the "$this->jsonHeaders" successfully and this does not give the error.)
I am running a test to confirm that when I try to post a request to create a product with an empty name, that the JSON response has 'The name field is required.' Moreover the status of the of the response should be 422 - Unprocessable Entity.
However, though the ProductController validates that the name is required:
class ProductController extends Controller
{
public function index() {
return Product::paginate();
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:products',
]);
return Product::create([
'name' => $request->input('name')
]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required|unique:products',
]);
$product = Product::findOrFail($id);
$product->update([
'name' => $request->input('name')
]);
return $product;
}
}
The test that fails is as follows:
public function testCreateProductFailsIfNameNotProvided()
{
$product = factory(Product::class)->make(['name' => '']);
$this->post(route('products.store'), $product->jsonSerialize())
->seeJson(['name' => ['The name field is required.']])
->assertResponseStatus(422);
}
The testing is command line phpunit with the following output:
There was 1 failure:
1) ExampleTest::testCreateProductFailsIfNameNotProvided
Invalid JSON was returned from the route. Perhaps an exception was thrown?
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:426
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:298
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:324
/home/vagrant/projects/demo/tests/ExampleTest.php:74
If the "->seeJson" line in the test is commented off the following failure is recorded:
1) ExampleTest::testCreateProductFailsIfNameNotProvided
Expected status code 422, got 302.
Failed asserting that 302 matches expected 422.
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:744
/home/vagrant/projects/demo/tests/ExampleTest.php:75
Laravel Framework version 5.3.26, testing phpunit, Laravel Homestead in Vagrant Box running in VM VirtualBox
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2g33g9I
via IFTTT
Aucun commentaire:
Enregistrer un commentaire