PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] Testing Laravel post requests using a Factory

 January 23, 2022     laravel-5, tdd     No comments   

Issue

I am writing some Feature tests for my Laravel application. I am new to TDD, so this may seem obvious to some.

LocationsFactory.php

use Faker\Generator as Faker;

$factory->define(App\Location::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
    ];
});

LocationsTest.php

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: Argument 2 passed to Illuminate\Foundation\Testing\TestCase::post() must be of the type array, object given

I understand the error is telling me that $location needs to be an array and it is an object. However, since I'm using a factory it's coming as an object. Is there a better way to use a factory in my test?

This also seems a bit off:

$this->assertDatabaseHas('locations', ['name' => $location->name]);

Since I am using faker, I have no idea what the name will be. So I'm just checking for whatever was generated is that ideal?

Thank you for any suggestions!

EDIT

Doing something like this works fine (and maybe that's the solution)...

...
$user = factory(User::class)->make();
$location = factory(Location::class)->make();

$response = $this->actingAs($user)->post('/locations', [
    'name' => $location->name
]);

$response->assertStatus(200);
$this->assertDatabaseHas('locations', ['name' => $location->name]);

However, let's say my location has 30 attributes. That seems like it could get ugly quick.


Solution

Laravel 5

Use toArray() for object to array conversion : see following example

    $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]);


Answered By - Rashedul Islam Sagor
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing