Search code examples
unit-testingcommand-linelaravel-5laravel-testing

How to Call command line from TestCase in Laravel 5


I am developing an application in Laravel 5, I have a test file which extends from TestCase.php, I need to call the phpcs command in my file

 class MyTest extends TestCase {

    public function testFunction()
    {
        //here I need to call the phpcs command                  
     }
  }

In te examples here http://laravel.com/docs/5.0/testing I just found the this->call function, which I don't think is the proper choice for me, since it is returning a response object, what is the right way to do it? which Class and functions should I use to to run a command-line inside this class I also need to have the result of the command in a variable


Solution

  • I don't Laravel has something built in for calling the command line. However it doesn't really need to because you can simply use the exec() function. Basically something like this:

    public function testFunction()
    {
        exec('phpcs', $output);
        echo $output[0]; // output line 1
    }
    

    As second argument you can pass a variable that will contain every line of the output as an array. The exec() function itself returns the last line from the output as string. (Especially useful when running single line commands like php -v)