mardi 29 août 2017

Laravel Unit Test api controller : compare two models result

i'm trying to use for the first time unit tests for my future projects. But i'm blocked with storing a model.

This is the api controller i want to test :

public function store(QuestionFormRequest $request)
{
    $questionRequest = $request->question();

    $question = new Question($questionRequest);
    $question->save();

    $question->answers()->createMany($questionRequest['answers']);

    return response()->json($question->load('answers'), 201);
}

This is my test :

public function it_can_store_a_question()
{
        $surveyFactory = factory(Survey::class)->create();
        $themeFactory = factory(Theme::class)->create();
        $pillarFactory = factory(Pillar::class)->create();

        $questionToStore = [
            'survey_id' => $surveyFactory->id,
            'theme_id' => $themeFactory->id,
            'pillar_id' => $pillarFactory->id,
            'name' => 'question',
            'type' => 'simple',
            'answers' => [
                [
                    'label' => 'reponse1',
                    'points' => '3',
                ],
                [
                    'label' => 'reponse2',
                    'points' => '5',
                ]
            ]
        ];

        $response = $this->post('/api/1.0/question', $questionToStore);
        $response->assertStatus(201);

        $expectedQuestion = Question::with('answers')->get()->first();
        $this->assertEquals(json_encode($expectedQuestion), $response->getContent());
} 

this is the result :

Failed asserting that two strings are equal.
Expected :'{"id":1,"survey_id":1,"theme_id":1,"pillar_id":1,"name":"question","type":"simple","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null,"answers":[{"id":1,"question_id":1,"label":"reponse1","points":3,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null},{"id":2,"question_id":1,"label":"reponse2","points":5,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null}]}'
Actual   :'{"survey_id":1,"theme_id":1,"pillar_id":1,"name":"question","type":"simple","updated_at":"2017-08-29 08:54:45","created_at":"2017-08-29 08:54:45","id":1,"answers":[{"id":1,"question_id":1,"label":"reponse1","points":3,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null},{"id":2,"question_id":1,"label":"reponse2","points":5,"description":"","created_at":"2017-08-29 08:54:45","updated_at":"2017-08-29 08:54:45","deleted_at":null}]}'

In fact, the result is right. But not in the same order. What do I do wrong in my test ?

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2wFkAOv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire