Updating SpecSalad

I have missed a couple of updates to SpecFlow recently and decided to do a catch up for my little testing framework SpecSalad.  With this update the framework now supports the latest version of both SpecFlow (1.9.0) and also the latest version of NUnit (2.6.1).

There has also been a couple of tidy up which I have been meaning to do for a while, most notably the ability to now save and retrieve values from both Roles and Tasks which should make tasks more flexible in the future.

As usual its all available on Nuget, and surprisingly this little framework is now heading towards its first 1000 downloads!

Thanks to all those who have been using the framework

Posted in Programming | Leave a comment

New update to SpecSalad

It has been a while since I have blogged, and actually done any development outside of work, the joys of releasing a new product to market; but with the holiday I took the opportunity to have a look at some of my home projects, among them SpecSalad.

The other day Mick Hanson blogged about SpecSalad, saying some very nice things about the framework, thanks Mick its great to see the framework being used and proving useful; but not only has he used the framework he has contributed some new scenario syntax, expanding what is a very limited vocabulary.

Mick’s changes bring eight new ‘Then’ scenario syntax sentences

Then I can Task Name (: or ,) Expected Context
Then you can Task Name (: or ,) Expected Context

Then I am able to Task Name (: or ,) Expected Context
Then I are able to Task Name (: or ,) Expected Context

Then you am able to Task Name (: or ,) Expected Context
Then you are able to Task Name (: or ,) Expected Context

Then the Role can Task Name (: or ,) Expected Context
Then the Role is able to Task Name (: or ,) Expected Context

which brings some much needed flexibility to the framework.

Along with Mikes updates I have also updated the wiki with the new syntax, and released a new Nuget package and upping the version number to 1.6.0.

Posted in Code | Tagged | Leave a comment

Test Driven Development

I am planning on giving a talk, tutorial, lecture, rant (take your pick), about my take on the whole test driven development movement, how to do it, the pitfalls to avoid and the improvements in production that can be achieved, so for those that are going to see the talk, this is a sort of primer, over the next few posts I hope to give a taste for where I will be going, and for everyone else, I hope it is helpful, inspirational or at lest interesting.

First up a warning, driving production code from tests is a paradigm shift in thinking and not to be taken lightly. Looking up paradigm in the Oxford English Dictionary it says

                                    “a pattern or model, an exemplar”

So I am going to be messing with your model of programming, its not an easy journey and its not a silver bullet that will solve all your development woes, in fact it can add to them if used incorrectly, but the results can be breath taking and well worth the journey. 

Like a lot of systems the rules appear simple, but to implement them successfully takes practice, and discipline, so don’t expect to get it right first time, like all good things it takes practice, practice, practice,

The rules for test driven development were defined by Robert C. Martin some time ago, and work for any of the test driven methodologies.

1. You are not allowed to write any production code, unless it is to make a failing test pass.

2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

3. You are not allowed to write any more production code than is sufficient to pass the one failing test.

So what does this actually look like in the real world of programming?

Notice we are not writing the test first that’s important! We are writing the test and production code stubs ( a stub in this context is the outline of a method, function, class, property as required to get code to compile.) along side each other so the test code leads the production code by a very few keystrokes. 

Once the test assertion is written, then we have a truly failing test because the production code has no inner core, which we can now fill out in the simplest way possible to make the test pass before moving on to the next test. 

Notice I said the simplest way possible, this is also important!

What we want to do is write the smallest, and simplest code that will make the test (and any previously passing tests) work, don’t worry about method size, single responsibility etc. they get sorted in the next stage, we want the test to pass first, and fast.

Watching others and myself work, it is this last stage when things start to go wayward, I have a failing test, and I begin to make it pass using what I know in my mind will be the final version of the code, ( I just know I am going to need that service for login and the logging to record and the service to the database etc. etc.) and before I look around I have been writing code for 30 minutes and the test is still failing!

I actually think it is at this point your coding partner should be shouting YAGNI (You Aren’t Going To Need It) in your ear.

Rule 3 is one of the most difficult to follow successfully.  Is adding all that extra stuff the simplest thing?  Or  am I adding what I think I know I will need? 

One of the tenets of test driven development is that the tests drive the design of the code, yes you will have an idea that you will probably need x and y services and the REST schema will help define how the controllers in your MVC application will be laid out. 

But these ideas should be born out by the tests. I have found that if the tests are allowed to drive the final design then surprising things happen, the code I arrive at is not the code I would have written! It is cleaner, readable and simpler that my original thoughts, and its always easier to maintain and extend.

What makes this transformation? once a test passes, we pause, we have working code, sit back, review it, read it and then look at the code from a totally different angle, what methods are doing more than one thing? does the class have the correct responsibilities? is the naming correct?

Now dive in and refactor it.

I am a big believer in small methods and the single layer of abstraction within a method, a method should do one thing, so I use the extract method refactoring until essentially I cant do it any more. 

The class with all these methods in should have one reason to exist, and only have a single reason to change, if any of the methods don’t conform to this then it’s a clue that I need a new class to handle that responsibility, and so again I refactor, all the time the tests are being run to ensure that I have not broken anything. 

During this period of change or moulding I will change the names of methods to reflect what they actually do, ensuring that the public facing method names are small and concise and that the internal private methods are long and descriptive. 

For each class and method in my project this refactoring can take place many times, each time a test passes, I can if I want to review the whole of my code base, this refactoring is not just limited to my production code either, the test code can be reviewed and cleaned up as well, here I am aiming for readability above all else and ensuring that any new classes created by the refactoring of the production code are now covered by new or moved tests. 

Readability in the test code is paramount, if having some code duplication in the tests improves readability I will have duplication, but in the production code, I will remove any sense of duplication, for production code I am looking for clean, concise, fast code, in the tests I am looking for readability, first and foremost.

This process of writing simple code that with each test provides functionality is what makes test driven development different and difficult to do.  Forcing the simplest thing that can possibility work, knowing that the next test will probably change it, can be difficult to grasp, why then am I writing the simple one line? why not write the more complex code that I know is going to be there?

Because I know I am going to change it, the act of writing it, then changing it a few moments later is what makes test driven code so unique, the code is being moulded by the tests and refactoring, code being changed is alive and dynamic, working in the fashion produces code that is simple, easily extendable and productive, and never what you originally thought of.

Like modelling clay, code is kept moving by the process, changing its shape all the time, never settling too long in any one pattern, but improving by design as the product evolves. 

This ability to change is what makes the practice special and fit the agile mould.  Code is not a static concept, test driven code is not written and left, it is forever being added to, amended and moulded, keeping the code clay moving means change is not only expected but welcomed. 

The codes ability to absorb change means the business is not going to expend money re-writing an application to adapt to new conditions, the current application can be changed to match the new business requirements.

Keeping the code moving is the developers job, we are responsible to the businesses for the source code, we should not want the code to “set”, because code that is left, rots and is difficult to change which impedes the business we are employed to support.

It is the use of tests, the practice of refactoring and test driven metrologies that allow a developer to keep the code mobile, meeting the business needs and supporting not preventing growth.

So that’s the advert over, next post we can actually get down to some code

Posted in Programming | Tagged , , | Leave a comment

Spec Salad Update

I uploaded a new version of spec salad to the Nuget library today. Primarily this is a compatibility update with the new version of SpecFlow v1.7, and a couple of bug fix’s that I have noticed when using the framework.

There is now syntax for calling a task from a role within the “Given” section of a scenario definition

Given the role attempts to task
Given the role attempts to task: single parameter or name “value pairs”
Given the role attempts to task, single parameter or name “value pairs”
Given the role was able to task
Given the role was able to task: single parameter or name “value pairs”
Given the role was able to task, single parameter or name “value pairs”
Given the role were able to task
Given the role were able to task: single parameter or name “value pairs”
Given the role were able to task, single parameter or name “value pairs”
Given the role did task
Given the role did task: single parameter or name “value pairs”
Given the role did task, single parameter or name “value pairs”

Improved error handling, I discovered that is a role was called that was not previously defined a key not found error was raised, this has been changed so that a SpecSalad exception is now raised with a message stating that the role has not been defined within the scenario.

Because of the update to Specflow 1.7, upgrading from previous versions of SpecSalad you will have to regenerate the code behind file for all the fixture files, as per the upgrade instructions  for Specflow.

I hope people are finding the framework useful, feed back is very welcome, the source is available on git hub here.

Posted in Programming | Tagged , | 6 Comments

Multiple Roles for SpecSalad

I have uploaded a new version of the SpecSalad framework to both the Nuget gallery and Github

The breaking news is the introduction of multiple roles for a scenario, prior to this release SpecSalad could only define a single role for a scenario, with this new release multiple roles can be defined at the start of a scenario, allowing the scenario text to more closely match the business scenarios where more than a single person or process is involved. 

Data and complete objects can be passed between these roles using the currently available save and restore functionality available from the application role base class.

So how does this work? 

Taking the example from the Codebreaker game in a previous post, we can change the codebreaker submits guess scenario to make the intent clearer, currently the text had to say that the codebreaker set the secret code.

Scenario Outline: submit guess
    Given I am a codebreaker
    And I did set the code to, <code>
    When I attempt to submit a guess: <guess>
    Then I should see screen text that includes: <mark>

When in fact is should state that another component sets the code, which the codebreaker is then trying to guess. 

Using the new multiple roles feature the text can now make this separation clear, specifying who is responsible for setting the secret code.

Scenario Outline: submit guess
    Given I am a codebreaker
    And there is a secret code generator
    When the secret code generator did set the code to: <code>
    And I attempt to submit a guess: <guess>
    Then I should see screen text that includes: <mark>

This rewritten scenario now explicitly states how the secret code is set, and that this responsibility is separate from the codebreaker role.

the new role class is created in exactly the same way as before stored within the roles directory and inheriting from the ApplicationRole

  1. public class SecretCodeGenerator : ApplicationRole
  2. {
  3.     public void SetSecretCodeTo(string code)
  4.     {
  5.         var codeGenerator = new Mock<ISecretCodeGenerator>();
  6.  
  7.         codeGenerator.Setup(x => x.GenerateCode()).Returns(code);
  8.  
  9.         this.StoreValue("SecretCodeGenerator", codeGenerator.Object);
  10.     }
  11. }

The code here is almost identical to the original code in the codebreaker role, the important change from the original is the last line this stores the code generator mock object so that it can be accessed by the codebreaker role when required.

Several changes have been made to the codebreaker role, after the removal of the secret code generator calls. 

The submit guess method was changed so that it calls the start game before calling the games guess method

  1. public void SubmitGuess(string guess)
  2. {
  3.     StartTheGame();
  4.  
  5.     _game.Guess(guess);
  6. }

The “start the game” method was tidied up, removing the creation of the secret code generator mock, moving the call to a property that will return the required secret code generator..

  1. public void StartTheGame()
  2. {
  3.     _screen = new StubScreen();
  4.  
  5.     _game = new Game(_screen, SecretCodeGenerator);
  6.  
  7.     _game.Start();
  8. }

The new secret code generator property attempts to retrieve the generator using the application role base class call to retrieve, which returns the generator defined in the secret code generator role, a check is made to ensure we have retrieved a generator before returning it.

  1. ISecretCodeGenerator SecretCodeGenerator
  2. {
  3.     get
  4.     {
  5.         var toReturn = (ISecretCodeGenerator) Retrieve("SecretCodeGenerator");
  6.  
  7.         if (toReturn == null)
  8.         {
  9.             var mock  = new Mock<ISecretCodeGenerator>();
  10.             mock.Setup(x => x.GenerateCode()).Returns("0");
  11.  
  12.             toReturn = mock.Object;
  13.         }
  14.  
  15.         return toReturn;
  16.     }
  17. }

The check for a retrieved value is required because the start game scenarios also call the “start the game” method and because these scenarios have no interest in the secret code they do not define a generator, so to ensure that these scenarios pass a default generator is defined that simply returns zero.

The SpecSalad syntax has been updated allowing scenario step to define a role, and state which role is to carry out the scenario step task.

This new syntax is compatible with scenarios written with a previous version of the framework.

Posted in Programming | Tagged , | 2 Comments

SpecSalad update

I have updated SpecSalad with a new feature today, ApplicationRoles is now a base class which all roles must inherit from, this base class contains the functionality to save and retrieve values.  This will allow a task to store important values within the scenario context for later use, using the traditional key value pair.

So a feature

Scenario: Save a value
    Given I am a specified role
    When I attempt to store: the value '3'
    Then I should retrieve the answer '3'

Can call a task, telling the role to store a value

  1. public class Store : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         Role.StoreValue("the_value", Details.Value_Of("the_value"));
  6.  
  7.         return null;
  8.     }
  9. }

and later in the scenario retrieve the value, in this case returning it to do the scenario assert.

  1. public class RetrieveTheAnswer : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         return Role.Retrieve("the_value");
  6.     }
  7. }

I have also added a new feature to show the use of the background: scenario step, and updated the readme file.

These updates are available in SpecSalad version 1.2 on the Nuget gallery.

Posted in Programming | Tagged , | Leave a comment

SpecSalad Part 2

In the last post I completed the start game feature, In this part I am going to be working on the submit guess feature.

  1. Feature: Code-breaker submits guess
  2.     The codebreaker submits a guess of four numbers.
  3.     The game marks the guess with + and – signs
  4.  
  5.     For each number in the guess that matches the number and
  6.     position of a number in the secret code, the mark includes one
  7.     + sign.
  8.     
  9.     For each number in the guess that matches the number but not the
  10.     position of a number in the secret code, the mark inclues one
  11.     – sign.
  12.  
  13. Scenario Outline: submit guess
  14.     Given I am a codebreaker
  15.     And I did set the code to, <code>
  16.     When I attempt to submit a guess: <guess>
  17.     Then I should see screen text that includes: <mark>
  18.  
  19.     Scenarios: no matches
  20.     | code | guess | mark |
  21.     | 1234 | 5555  |      |
  22.     
  23.     Scenarios: 1 number correct
  24.     | code | guess | mark |
  25.     | 1234 | 1555  | +    |
  26.     | 1234 | 2555  | –    |
  27.  
  28.     Scenarios: 2 numbers correct
  29.     | code | guess | mark |
  30.     | 1234 | 5254  | ++   |
  31.     | 1234 | 5154  | +-   |
  32.     | 1234 | 2545  | —   |
  33.  
  34.     Scenarios: 3 numbers correct
  35.     | code | guess | mark |
  36.     | 1234 | 5234  | +++  |
  37.     | 1234 | 5134  | ++-  |
  38.     | 1234 | 5124  | +–  |
  39.     | 1234 | 5123  | —  |
  40.  
  41.     Scenarios: all numbers correct
  42.     | code | guess | mark |
  43.     | 1234 | 1234  | ++++ |
  44.     | 1234 | 1243  | ++– |
  45.     | 1234 | 1423  | +— |
  46.     | 1234 | 4321  | —- |

Running the first scenario of the submit guess feature throws this error

image

I create the task SetTheCodeTo, this tells the role to set the secret code to a given value

  1. public class SetTheCodeTo : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         var code = Details.Value();
  6.  
  7.         Role.SetSecretCodeTo(code);
  8.  
  9.         return true;
  10.     }
  11. }

The details object accessed from the ApplicaitonTask base class contains all the parameters supplied in the scenario step, in this case there is just a single value, so I can use the Value method that returns the first value in the details, if there was more than a single value, they would be defined in the scenario step with keys for example

  1. When I attempt to subtract: the number '<subtractor>' from the number '<subtractee>'

in this case I would use the Value_Of method of details which requires a key, in the above example the first value has the key “the_number” the second value has the key “from_the_number”.

The role method SetSecretCodeTo after some refactoring simply calls the start game method with the required secret code

  1. public void StartTheGame(string code = "0")
  2. {
  3.     _screen = new StubScreen();
  4.     var codeGenerator = new Mock<ISecretCodeGenerator>();
  5.  
  6.     codeGenerator.Setup(x => x.GenerateCode()).Returns(code);
  7.  
  8.     _game = new Game(_screen, codeGenerator.Object);
  9.  
  10.     _game.Start();
  11. }
  12.  
  13. public void SetSecretCodeTo(string code)
  14. {
  15.     StartTheGame(code);
  16. }

The start game method has been changed to accept a secret code which is defaulted to zero using a net 4.0 optional parameter, this value is returned by the mock secret code generator, finally the start method is called which in the game class will call the generator and store its returned value.  Running the tests again, I get the following error

image

The new submit a guess task, gets the guess from the scenario step using the value method, and hands it onto the role submit guess method.

  1. public class SubmitAGuess : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         var guess = Details.Value();
  6.  
  7.         Role.SubmitGuess(guess);
  8.  
  9.         return true;
  10.     }
  11. }

 

The role submit guess method has to simply call the games guess method and hand in the players guess.

  1. public void SubmitGuess(string guess)
  2. {
  3.     _game.Guess(guess);
  4. }

I have already refactored the feature to use the same view screen task

  1. Scenario Outline: submit guess
  2.     Given I am a codebreaker
  3.     And I did set the code to, <code>
  4.     When I attempt to submit a guess: <guess>
  5.     Then I should see screen text that includes: <mark>

so when I run the acceptance tests I get the expected failure

image

The error occurs because nothing has been written in the submit guess method, so the screen output collection only includes the lines added during the game start, to get this scenario to pass I added a call to writeline with an empty string in the game guess method.

  1. public void Guess(string guess)
  2. {
  3.     _output.WriteLine("");
  4. }

I now have my first passing test, there is no more code to be written in the acceptance tests,  and getting them all to pass now requires the logic to be added to the games guess method, this is going to be more complex than a simple one line change and so I will create a unit test project, and using this finer grain of testing, drive out the required functionality so that all the acceptance tests pass. 

The features I have written for my game form the framework within which I write the production code, and where required unit tests.  how do I decide when unit tests are required? 

If I can’t make the scenario step pass with a simple line of code, either new code or calling an already established method, then unit tests are required, for example I didn’t feel the need to unit test any of the game start code, as this was almost all to do with writing out to the screen, simple calls to WriteLine, however the calls to guess now need some logic to mark the guess against the secret code so I will unit test this, but always with a view to getting the scenario steps to pass, working from the most simple case towards the most complex.

In the future when I look at the unit tests I should be able to see the flow back towards the feature that caused the unit tests existence, using this technique I have found that the tests become more focused, they become the scaffolding within which I am writing my production code, and although there are fewer, they cover the code better and allow for the codebase to expand and change in the future.

Spec Salad has allowed me to avoid the monolithic step definition file which can be difficult to navigate, instead replacing it with a roles and tasks that are directly linkable to the feature text, more focused and easier to navigate in the future. 

The project layout for code breaker also shows how the split between features, roles and tasks helps with the reading of the codebase, all the actual doing code is contained within the roles, whilst the tasks are responsible for calling the correct role method with the required parameters.

image

The full source code for the code breaker project is available on Github, along with the source for SpecSalad.

SpecSalad is also available as a Nuget package, this will automatically add SpecSalad, SpecFlow and NUnit to the project along with the required configuration in the projects app.config.

If this style of behaviour driven design is of interest then I can recommend the RSpec book, although the language used is Ruby the techniques taught are universal.

Posted in Uncategorized | Leave a comment

SpecSalad Part 1

I have updated SpecSalad and also at last pushed it up to the Nuget gallery, when it is installed, it also installs SpecFlow and NUnit, along with adding a reference to the spec salad dll  in the step assemblies node of the application config, so it is ready for use.

SpecSalad is a c# implementation of the RiverGlide CukeSalad framework, which is designed to eliminate monolithic step definition class files associated with the standard spec flow style of development.  In many projects there comes a point where finding the way around the various step definitions is done more on experience of where the actual method is within the file rather than any specific layout or pattern! Spec Salad uses Roles and Tasks present an easy and descriptive layout, that makes moving between the feature text, test code and implementation easier.

How does the framework look in a solution? Inspired by the great RSpec Book lets make the game code-breaker! to show the framework in action.

I have uploaded the code to GitHub, The important part to aid navigation is the layout of the test project, in this I create folders that will contain features, roles and the tasks.

image

I start with the features, these define what I am trying to do, and provide me with a simple definition of what done will look like.

  1. Feature: Code-breaker starts game
  2.     As a code-breaker
  3.     I want to start a game
  4.     So that I can break the code
  5.  
  6. Scenario: start game
  7.     Given I am a codebreaker
  8.     When I attempt to start the game
  9.     Then I should see screen text that includes: 'Welcome to Codebreaker!'
  10.     And I should see screen text that includes: 'Enter guess:'

 

  1. Feature: Code-breaker submits guess
  2.     The codebreaker submits a guess of four numbers.
  3.     The game marks the guess with + and – signs
  4.  
  5.     For each number in the guess that matches the number and
  6.     position of a number in the secret code, the mark includes one
  7.     + sign.
  8.     
  9.     For each number in the guess that matches the number but not the
  10.     position of a number in the secret code, the mark inclues one
  11.     – sign.
  12.  
  13. Scenario Outline: submit guess
  14.     Given I am a codebreaker
  15.     And I did set the code to, <code>
  16.     When I attempt to submit a guess: <guess>
  17.     Then I should see on the screen '<mark>'
  18.  
  19.     Scenarios: no matches
  20.     | code | guess | mark |
  21.     | 1234 | 5555  |      |
  22.     
  23.     Scenarios: 1 number correct
  24.     | code | guess | mark |
  25.     | 1234 | 1555  | +    |
  26.     | 1234 | 2555  | –    |
  27.  
  28.     Scenarios: 2 numbers correct
  29.     | code | guess | mark |
  30.     | 1234 | 5254  | ++   |
  31.     | 1234 | 5154  | +-   |
  32.     | 1234 | 2545  | —   |
  33.  
  34.     Scenarios: 3 numbers correct
  35.     | code | guess | mark |
  36.     | 1234 | 5234  | +++  |
  37.     | 1234 | 5134  | ++-  |
  38.     | 1234 | 5134  | +–  |
  39.     | 1234 | 5123  | —  |
  40.  
  41.     Scenarios: all numbers correct
  42.     | code | guess | mark |
  43.     | 1234 | 1234  | ++++ |
  44.     | 1234 | 1243  | ++– |
  45.     | 1234 | 1423  | +— |
  46.     | 1234 | 4321  | —- |

They look like fairly standard SpecFlow features, which they are, only the syntax of each of the scenario steps is important to the spec salad framework.

The currently allowable syntax is

Given [I am | you are] a <role>

Given [I | you] [attempt to | was able to | were able to | did] <task>[: | ,] <parameters>

When [I |you] [attempt to | was able to | were able to | did] <task>[: | ,] <parameters>

Then [I | you] should <question> ‘<answer>’

Then [I | you] should <question> that includes: <answer>

Then [I | you] should <question>

Starting with the first feature, which requires that the game displays a title and prompt at start up, running the feature, I get the following error.

image

The error states I need to create a role or task called ‘codebreaker’, once I have created a class in the roles folder, that inherits from the ApplicationRole base class, and rerun the feature again I get a new error.

image

the error raised this time requires a role or task called “StartTheGame”,  this is the task that the role will carry out.

I created the class in the tasks folder, this class inherits from the ApplicationTask base class, which requires me to implement the PerformAction method, in this method, I tell the role what to do, in this case to start the game.

  1. public class StartTheGame : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         Role.StartTheGame();
  6.  
  7.         return true;
  8.     }
  9. }

 

SpecSalad defines the Role as dynamic, which means that this task will work for any role that implements a StartTheGame method that takes no parameters, so tasks are fully re-useable between different roles. 

Because role is stored in the scenario context of SpecFlow any variables set within the role will be preserved throughout the context without any extra work.

The Role now has to implement the StartTheGame method, and do something, in this case create the game class and call its start method

  1. public class Codebreaker: ApplicationRole
  2. {
  3.     public void StartTheGame()
  4.     {
  5.         var game = new Game();
  6.  
  7.         game.Start();
  8.     }
  9. }

running the test again I get a new failure, stating that I need to create a task ‘SeeTheScreen’

image

Again this is a task, that is going to tell the role to look at the screen and report what it sees, the task will then send this report to the system, which will compare it against the the expected screen text proposed in the scenario definition.

  1. public class SeeScreenText: ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         return Role.LookAtOutput();            
  6.     }
  7. }

 

The system comparer for includes syntax expects an IEnumerable to compare against, which the role method LookAtOutput will return. 

The role of cause cannot actually look at the screen, but there are various ways I can mock or stub looking at the standard output, I have chosen what I think is the simplest, an interface that will  implement a WriteLine method, and a stub class that implements this interface and stores each message in a collection.  This collection can then be returned by our role.

The final code looks like this.

  1. public class Codebreaker: ApplicationRole
  2. {
  3.     IOutput _screen;
  4.  
  5.     public void StartTheGame()
  6.     {
  7.         _screen = new StubScreen();
  8.         var game = new Game(_screen);
  9.  
  10.         game.Start();
  11.     }
  12.  
  13.     public IEnumerable<string> LookAtOutput()
  14.     {
  15.         return ((StubScreen)_screen).ReadMessages;
  16.     }
  17. }
  18.  
  19. public class StubScreen : IOutput
  20. {
  21.     readonly IList<string> _readMessages = new List<string>();
  22.  
  23.     public void WriteLine(string message)
  24.     {
  25.         _readMessages.Add(message);
  26.     }
  27.  
  28.     public IEnumerable<string> ReadMessages { get { return _readMessages; } }
  29. }

This gives us our first truly failing test

image

To make this scenario pass I now simply need to write the two expected output lines within the start method.

  1. public class Game
  2. {
  3.     readonly IOutput _output;
  4.  
  5.     public Game(IOutput output)
  6.     {
  7.         _output = output;
  8.     }
  9.  
  10.     public void Start()
  11.     {
  12.         _output.WriteLine("Welcome to Codebreaker!");
  13.         _output.WriteLine("Enter guess:");
  14.     }
  15. }

 

Running the tests again we now get a pass.

image

This looks like a good place to break this already very long post, ready to continue next time with the implementation and testing of the submit guess feature.

Posted in Programming | Tagged | 2 Comments

Spec Salad

I while ago I watched a talk by Antoney Marcano at skills matter about a new framework called cukesalad which sits on top of ruby cucumber and allows the test framework to be used without having to write step definitions.  The scenarios are defined using a syntax that focuses on the roles and tasks associated with the scenario.

I have been following Antony’s blog and like the way he has been pushing the scenario definitions, as it follows my own thoughts about the position of cucumber within the overall development process, and the writing of the specifications in a generic way that allows the design of the application to follow a more natural course, the scenarios should define the what not the how.

In day to day work I use Specflow, the dot net alternative to Cucumber, so I set about looking at converting the RiverGlide framework into C# to work with Specflow.

There are some changes to the detail. Tasks must inherit from ApplicationTask, which provides access to the current role and the details collection.  The role is defined as dynamic, which allows the framework to match any role that has the specified methods to this task, the details collection is made up from the parameters defined in the feature file as a name value collection.

Scenario Outline: Find the sum of two numbers
    Given I am a Calculating Individual
    And I was able to switch on the calculator
    When I attempt to add: the number '<first_number>' to the number '<second_number>'
    Then I should see the answer '<result>'

 

  1. public class Add : ApplicationTask
  2. {
  3.     public override object Perform_Task()
  4.     {
  5.         Role.Enter(int.Parse(Details.Value_Of("the_number")));
  6.         Role.Press('+');
  7.         Role.Enter(int.Parse(Details.Value_Of("to_the_number")));
  8.         Role.Press('=');
  9.  
  10.         return null;
  11.     }
  12. }

Roles must inherit from ApplicationRole, the role defines the implementation of the tasks that the role can carry out.

  1. public class CalculatingIndividual : ApplicationRole
  2. {
  3.     TheCalculator _calculator;
  4.  
  5.     public void Enter(int value)
  6.     {
  7.         _calculator.Enter(value);
  8.     }
  9.  
  10.     public void Press(char function)
  11.     {
  12.         if (function == '=')
  13.             _calculator.Equals();
  14.         else
  15.             _calculator.Get_Ready_To(function);
  16.     }
  17. }

 

Also because the spec salad framework actually contains the step definitions that tie these roles and tasks together, the app config of the test project, must have this additional spec flow child node.

    <stepAssemblies>
      <stepAssembly assembly="SpecSalad" />
    </stepAssemblies>

In order to match these predefined step definitions scenarios are written using a subset of the Gherkin language, this subset focuses on the role, and the tasks the role can perform.

Given <I am | you are> a <role>

  1. Given I am a specified role

And <I | you> <attempt to | was able to | were able to | did> <a task>:<with parameters>

  1. And I attempt to do the return task: with parameter '2' and parameter '3'

When <I | you> <attempt to | was able to | were able to | did> < a task>:<with parameters>

  1. When I attempt to do the return task: with parameter '2' and parameter '3'

And <I | you> <attempt to | was able to | were able to | did> < a taks>:<with parameters>

  1. And I attempt to do the return task: with parameter '2' and parameter '3'

Then <I | you> should <the question> ‘<expected answer>’

  1. Then I should see the answer '1'

performs an assert are equal between the expected answer and the roles answer to the given question
or
Then <I | you> should <the question> that includes: <expected answer>

  1. Then I should see the answers that includes: 1

performs an assert contains between the roles answer to the question and the expected content
or
Then <I | you> should <the question>

  1. Then I should see one

this doesn’t perform any asserts, but simply calls the roles answer method with the given question, it is expected that this method would carry out any required asserts.

 

You can find the source for this project here, I am hoping to create a Nuget package soon, which will make it easier to include in test projects.

Posted in Code | Leave a comment

Arguments For Agile

Corey Haines keynote at ACE (Agile Central Europe) puts succinctly why agile works, it’s a great keynote, and I am noting it here mainly for my own future reference, but it is well worth watching.

http://vimeo.com/22487205

Posted in Uncategorized | Leave a comment