mercredi 2 septembre 2020

LARAVEL cast colums JSON with feature test phpunit

does not pass me the last test that compares the field just entered with the one sent because json

I have the following fields:

public function up()
        {
            Schema::create('polls', function (Blueprint $table) {
                $table->id();
                $table->text('now');
                $table->json('paramJson');
                $table->enum('status', ['a', 'b', 'c','d'])->default('a');
            });
        }

Poll model:

protected $fillable=[
                'now',
           'paramJson',
            ];

//to cast that column from JSON to an array automatically (maybe it doesn't work)
protected $casts = [
                'paramJson' => 'array',
            ];

PollsController.php

public function add(Request $request)
    {
        $poll = Poll::create($request->all());
        return response()->json($poll, 201);
    }

Feature/PollApiTest.php

    $data = [
       "now" => "Will Messi sign for City?",
       "parameters" : {"a"=> "yes", "b"=> "no"},
    ];

    $response = $this->post('/api/polls',$data);//add data in polls

    $response ->assertStatus(201);// assert Ok

    $response->assertJson($data);//assert Ok

    $response = $this->get('/api/poll');//get index polls

$this->assertSame($dataDbTest[0]['paramJson'],$data['paramJson']);//this test fails

the last test fails because below the error

Failed asserting that Array &0 ( 'a' => 'yes' 'b' => 'no' ) is identical to '{"a": "yes", "b": "no"}'.

if the last test I do it with json_encode:

$this->assertSame($dataDbTest[0]['paramJson'],json_encode($data['paramJson']));

--- Expected
+++ Actual @@ @@
-'{"a": "yes", "b": "no"}'
+'{"a":"yes","b":"no"}'

Aucun commentaire:

Enregistrer un commentaire