October 22, 2015

An Introduction to Scoped Bindings in SpecFlow

One nice aspect of SpecFlow is the ability to scope bindings by feature title, scenario title, or tag. Normally bindings are global to the project, but a binding's scope can be restricted using the Scope attribute. I like to think of it as similar to the private and public class modifiers in C#.

Consider the Gherkin below.

It is a single feature with one scenario and two tags. One tag is at the feature level and the other at the scenario level.

The feature's corresponding steps can be scoped by:

Scenario Title

Scenario Tag

Feature Title

Feature Tag

In these snippets, the Scope attribute is applied at the class level, but you can also put them on individual methods. When the SpecFlow test runner executes the bindings, it will match the Gherkin to methods based on scoping rules. If there are multiple matches, the most restrictive match is used.

Same Gherkin, Different Bindings

To illustrate the usefulness of scoped bindings, consider the following feature that invokes a service with content serialized to XML, JSON, and Form-UrlEncoding. The text of the When step is the same in the Gherkin for all three scenarios, but each bound method is different. Without scoped bindings, this feature won't run because the SpecFlow runtime can't determine which method to execute.

Scoped bindings can help. You could scope each method by scenario title.

Or use tags.

While this example works well for demonstrating the power of scoped bindings, I generally avoid coupling step definitions to Gherkin in all but the simplest features. In fact, this type of coupling has been identified as an anti-pattern.

So how would I fix this? That's the subject of my next post. In the meantime, you can read more about scoped bindings in the SpecFlow documentation.

© Joe Buschmann 2020