laravelphpspec

phpspec and laravel setup


I am setting up a new Laravel project and integrating PHPSpec. I am having trouble finding a good working example of the phpspec.yml file that would work neatly with Laravel. In a similar way to RSpec in Rails.

My desired folder structure would be as follows

spec/
    models/
    controllers/
app/
    models/
    controllers/

My phpspec.yml currently looks like this:

suites:
controller_suite:
    namespace: Controller
    spec_path: 'spec/controllers'
    src_path: 'app/controllers'

model_suite:
    namespace: Model
    spec_path: 'spec/models'
    src_path: 'app/models'  

I copied my Model related tests in the spec/models folder, but when I 'phpspec run' it does not run any of them. I also realise that the namespace is not 'Model' and 'Controller' in Laravel, perhaps more like Eloquent and BaseController..

I am also using this extension: https://github.com/BenConstable/phpspec-laravel

I'm not sure how to set this up and cannot find any working examples. Thanks in advance!

EDIT: Advice founbd on another forum from Jeffrey Way:

You can test your controllers with Behat. PHPSpec isn't a substitute for it (or Codeception).

UPDATE:

I've since decided to use Codeception instead as it seems to integrate neatly into Laravel and widely used.


Solution

  • Kindly answered via email from Ben Constable :

    Setting up PHPSpec with Laravel with its default file layout is pretty difficult, and I haven’t yet figured out how to do it. However, you can get it working with a slightly different layout, like:

    - app
        - Controllers
            - MyController.php
        - Models
            - MyModel.php
    - spec
        - Controllers
            - MyControllerSpec.php
        - Models
            - MyModelSpec.php
    

    then, in your phpspec.yml you’d have:

    extensions:
        - PhpSpec\Laravel\Extension\LaravelExtension
    
    suites:
        laravel_controller_suite:
            namespace: Controllers
            src_path: app
        laravel_model_suite:
            namespace: Models
            src_path: app
    
    laravel_extension:
        testing_environment: 'testing'
    

    and finally, you’d need to modify your composer.json to include app/ in the autoload class map. Your models, controllers and whatever would then be namespaced, like:

    <?php namespace Controllers;
    
    use Controller;
    
    class MyController extends Controller {}
    

    That should sort you out. Just as an aside, when I’ve been making Laravel projects I’ve been putting everything in app/src/MyVendor/MyNamespace/Controllers etc, which I prefer as a layout (keeps the source away from the config and other files, and is similar to the layout of Laravel Packages).

    In the future, I will try and look into it and see if I can get PHPSpec working with the default Laravel layout - I’ll update the project on GitHub if/when I do.