Wrapping a spec with a behavior

One very common use for a behavior is to wrap a spec in a transaction scope. This way, any changes the spec makes can be rolled back once the spec executes.

First, let's register the behavior:

WhenTesting<INeedATransaction>().EnrichWith<TransactionScopeWrapperBehavior>();

Now we just need the behavior and the marker interface:

public interface INeedATransaction : ISpecs
    {
    }

    public class TransactionScopeWrapperBehavior : Behavior<INeedATransaction>
    {
        private TransactionScope _scope;

        public override void SpecInit(INeedATransaction instance)
        {
            _scope = new TransactionScope();
        }

        public override void AfterSpec(INeedATransaction instance)
        {
            _scope.Dispose();
        }
    }

Any spec can now automatically wrap itself in a transaction scope just by implementing the INeedATransaction interface.


Did this page help you?