在 Behat 中使用上下文——正确的方法

Using Context in Behat - The right approach

在 behat 中使用 FooContext 类 的正确方法是什么?

docs 是什么:

A simple mnemonic for context classes is: “testing features in a context”. (...), the way you will test those features pretty much depends on the context you test them in.

在文档中 FeatureContext 对我来说似乎只是一个虚拟上下文文件,以便您可以快速创建行为测试。

The context class should be called FeatureContext. It’s a simple convention inside the Behat infrastructure. FeatureContext is the name of the context class for the default suite.

它不是直接告诉我它必须是每个功能的上下文文件。

文档中唯一真实的其他示例是 ApiContextWebContext 等上下文。

default:
    suites:
        web_features:
            paths:    [ %paths.base%/features/web ]
            contexts: [ WebContext ]
        api_features:
            paths:    [ %paths.base%/features/api ]
            contexts: [ ApiContext ]

我还发现了 CommandFeature and another CommandLineProcessContext

所以如果我有很多功能要测试,上下文文件会很快爆炸。

然后我看到 Marco Pivetta using an Aggregate as Context 的每个特征示例更有可能是一个上下文文件。

每个功能都有一个上下文文件是个好主意吗foo.feature?或者上下文文件是否被认为是文档中的环境上下文 ApiContextWebContext?

通常我更喜欢这样划分上下文和特征:

  • 每个域主题一个文件夹
  • 一个功能/上下文文件,用于您可以对此主题执行的每个操作

这样你最终会得到一个使用多个上下文但所有上下文都由单一责任划分的套件。

快速示例

Features
|--- User
|----- login.feature
|----- change_password.feature
|----- impersonate.feature
|----- ban.feature
|----- ...
|--- ...
|--- Order
|----- checkout.feature
|----- cancel.feature
...
Context
|--- User
|---- LoginContext
|---- ChangePasswordContext
|---- ImpersonateContext
|---- BanContext
|---- ...
|--- Order
|---- CheckoutContext
|---- CancelContext

每个套件由许多上下文组成(例如,每次您需要登录以检查行为时,您将在套件中包含 LoginContext)。

default:
  suites:
    suite_name:
      paths:
        - '%paths.base%/Path/To/Feature/File'
      contexts:
        - Path\To\Context\LoginContext
        - Path\To\A\SecondContext
        - ...

这种方式在可维护性、直观性等方面有很多优势。

如果您想获得有关此主题的更通用的全景图,可以check slides from my talk at Symfony day 2017 in Milan