Main Content

Behaviour Driven Development / Ruby and Cucumber

Archive - Originally posted on "The Horse's Mouth" - 2015-01-02 19:55:12 - Graham Ellis

 
Articles in this "Introduction to Cucumber" series:
[link] - Installing Cucumber for Ruby
[link] - Hello Test Cucumber World
[link] - First real tests / second example
[link] - Improved tests with RSpec
 




You write code to meet a requirement. The requirement is that it behaves in a certain way. So when you call up your code in a certain way, you get a certain response.

Behaviour Driven Developement is where you start off by describing how you want to call your code ("access certain features") and the responses that you want to get. Only when you have written those scenarios do you actually go ahead and write the code so that it meets the required behaviour.

This is a very logical way of working - after all "the customer is king" and the customer for your code is the user of that code.

Cucumber is a Ruby gem which provides users with the ability to specify what their code will be required to do (using an English like language such as Gherkin). It then gives them the ability to wrie the actual tests that are going to be done to check that the code will run as specified. And if you run your cucumber on your application at this point, you'll get a whole load of red messages telling you that your code doesn't work yet!



You then go ahead and implement, (write) the actual code that's needed to implement the specification, and keep running cucumber until ir works and goes all green.



As you enhance and develop your application, you'll add behaviours, then tests, then code to implement the behaviour that's required, and by rerunning cucumber you'll keep re-testing the previously implemented behavious so that you're assured than new features and behaviours haven't broken the previous ones.

The complete file set for this "Hello Cucumber World" example is:
  WomanWithCat:cuc grahamellis$ ls -R1 hello
  greet.rb Code to implement behaviour - 3rd and final file
  hello.feature Gherkin definition of feature - 1st file
  step_definitions
  
  hello/step_definitions:
  hello_steps.rb Ruby code to implement tests - 2nd file


Links:
1. Gherkin to describe - [here]
2. Ruby test specification - [here]
3. Implementation code - [here]

Behaviour and test driven developement becomes ever more important in our training courses, and in each of the public programming courses we teach we'll touch on the subject at the very least. Should it be appropriate for any of the delegate group we have we'll go deeper, as we will on private courses if so requested. Our public course schedule is [here], and most other weeks are avaibable for tailored private courses. At the time of writing (2nd January 2015), we have a busy private training schedule and apart from a few odd days, the next private course availability is for March.