Phpspec和Laravel的设置

4

我正在建立一个新的Laravel项目,并集成PHPSpec。 我很难找到一个能够与Laravel完美配合的phpspec.yml文件的好的工作示例。 与Rails中的RSpec类似。

我的期望文件夹结构如下:

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

我的phpspec.yml文件当前看起来像这样:

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'  

我将我的模型相关测试复制到spec/models文件夹中,但当我运行'phpspec run'时,它不会运行任何一个测试。我也意识到在Laravel中,命名空间不是'Model'和'Controller',可能更像'Eloquent'和'BaseController'。
我还使用了这个扩展:https://github.com/BenConstable/phpspec-laravel
我不确定如何设置它,也找不到任何可用的示例。谢谢!
编辑: Jeffrey Way在另一个论坛上提供的建议如下:
“您可以使用Behat测试您的控制器。PHPSpec不是它(或Codeception)的替代品。”
更新:
我后来决定改用Codeception,因为它似乎能够很好地集成到Laravel中,并且被广泛使用。

2
我知道你已经决定使用Codeception了,但是Laracasts(我相信是Jeffrey Way)上有一个免费的视频,介绍了如何在Laravel中使用phpspec。这个视频大约15分钟长,但我认为它值得花时间观看。https://laracasts.com/lessons/phpspec-laravel-and-refactoring - user1669496
@user3158900 谢谢,我会去看看的。看起来它更适合单元测试,而结合使用 phpspec 和 codeception 可能会更好。 - Adamski
2个回答

5

通过电子邮件友好地回答,发件人为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.


感谢Ben的帮忙,我完全不知道为什么我的代码不能正常运行,直到看到这个扩展。我甚至没有试图测试控制器和模型,只是在我的自定义类中抛出了一个错误,而这是在我的测试已经通过后发生的。 - alexleonard

2
对于使用 Laravel 5.x 和 PhpSpec 4.x 的用户,你可以调整 PSR4 前缀配置 来使 PhpSpec 兼容 Laravel 布局。
我的项目使用了这个配置:
suites:
    app:
        namespace: App
        src_path: app
        psr4_prefix: App
        spec_prefix: classes
        spec_path: specs

我为此苦苦挣扎了相当长的时间。结合spec_prefix和spec_path解决了问题,感谢分享。 - dajoto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接