Search code examples
mspec

MSpec Establish delegate


According to MSpec documentation here, Establish should run only once. However, when I debug the Establish is being run once per the It delegate. Here is a simple example:

public class TestExample
{
        Establish arrange = () =>
        {
            a = 5;
        };
        Because of = () => a = a * 2;
        It should_be1 = () => a.ShouldEqual(10);
        It should_be2 = () => a.ShouldBeGreaterThan(9);
        It should_be3 = () => a.ShouldBeLessThan(90);
        private static int a;
}

Should it run once per It delegate? Or once per the class?


Solution

  • It's once per context (class) - unless it has a base class in which case the base class's Establish executes first (recursively, as deep as the class inheritance tree).

    How are you determining that it is executing multiple times?

    For what it's worth, I cannot reproduce this behaviour using MSpec 0.9.0, the ReSharper runner and the exact code from the question. All of the specs execute and the Establish executes once, as expected.

    Sprinkling a few Console.WriteLine() as follows:

    using System;
    using Machine.Specifications;
    
    namespace StackOverflow_26809460
        {
        public class TestExample
            {
            static int a;
    
            Establish arrange = () =>
                {
                a = 5;
                Console.WriteLine("Establish");
                };
    
            Because of = () => a = a*2;
    
            It should_be1 = () =>
                {
                a.ShouldEqual(10);
                Console.WriteLine("should_be1");
                };
    
            It should_be2 = () =>
                {
                a.ShouldBeGreaterThan(9);
                Console.WriteLine("should_be1");
                };
    
            It should_be3 = () =>
                {
                a.ShouldBeLessThan(90);
                Console.WriteLine("should_be1");
                };
            }
        }
    

    When I run that in the command line runner, I get:

    
    Specs in StackOverflow_26809460:
    
    TestExample
    Establish
    should_be1
    » should be1
    should_be1
    » should be2
    should_be1
    » should be3
    
    
    Contexts: 1, Specifications: 3, Time: 0.53 seconds
    
    C:\Users\Tim\Projects\StackOverflow\StackOverflow_26809460\bin\Debug>

    It looks like a runner issue to me...