How to test form request rules in Laravel 5?

前端 未结 2 1223
自闭症患者
自闭症患者 2020-12-31 14:22

I created a form request class and defined a bunch of rules. Now I would like to test these rules to see if the behaviour meets our expectations.

How could I write a

相关标签:
2条回答
  • 2020-12-31 14:48

    You need to have your form request class in the controller function, for example

    public function store(MyRequest $request)
    

    Now create HTML form and try to fill it with different values. If validation fails then you will get messages in session, if it succeeds then you get into the controller function.

    When Unit testing then call the url and add the values for testing as array. Laravel doc says it can be done as

    $response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);
    
    0 讨论(0)
  • 2020-12-31 15:09

    The accepted answer tests both authorization and validation simultaneously. If you want to test these function separately then you can do this:

    test rules():

    $attributes = ['aa' => 'asd'];
    $request = new MyRequest();
    $rules = $request->rules();
    $validator = Validator::make($attributes, $rules);
    $fails = $validator->fails();
    $this->assertEquals(false, $fails);
    

    test authorize():

    $user = factory(User::class)->create();
    $this->actingAs($user);
    $request = new MyRequest();
    $request->setContainer($this->app);
    $attributes = ['aa' => 'asd'];
    $request->initialize([], $attributes);
    $this->app->instance('request', $request);
    $authorized = $request->authorize();
    $this->assertEquals(true, $authorized);
    

    You should create some helper methods in base class to keep the tests DRY.

    0 讨论(0)
提交回复
热议问题