TDD / BDD

TotT 2014

TDD

Test-driven development is a short, repetitive process.

  1. Write a failing test case for an enhancement (red)
  2. Implement the minimum code to pass the test (green)
  3. Refactor the code to meet project standards (refactor)

Benefits

  • Focus on requirements
  • Short development cycles
  • Safety net for refactoring
  • Forces thoughts about design

Use Cases

  • Maximizing test coverage
  • Supporting continuous integration
  • Improving legacy code

But what do you test?

BDD

Behavior-driven development builds on TDD.

  1. Specify desired behavior in a consistent format
  2. Write a failing test case for a scenario
  3. Implement the minimum code to pass the test
  4. Refactor the code to meet standards

Use Cases

  • Outlining required tests
  • Communicating with stakeholders
  • Documenting design decisions

But what is a consistent format?

One Format: Gherkin

  • Domain specific language
  • Business readable
  • From Cucumber BDD (Ruby)
  • Documents behavior
  • Binds to test cases

Example: Gherkin

Feature: App store validates customer credit card

Scenario: First-time customer
  Given a customer is unknown
  When the customer checks out
  Then the checkout process should prompt for cc info
  
Secnario: Customer credit card expired
  Given a customer is known
  And the cc on-file is expired
  When the customer checks out
  Then the checkout process should prompt for new cc info
  
...

Behave

"behave is behaviour-driven development, Python style. ... [It] uses tests written in a natural language style, backed up by Python code."
- pythonhosted.org/behave

Components

  • Feature files contain Gherkin scenarios
  • Step files contain test code
  • behave CLI binds the two

Demo: Fibonacci Numbers

Spec, test, code, refactor

Demo: Fibonacci Numbers

What about non-trivial units?

Say I have a class that uses a database?

Dependency Injection

  • Make components pluggable
  • In production, use real objects (e.g., database)
  • In test, use "fakes" (e.g., stub database)

To Be Continued

We'll need a whole other session

Is Gherkin the only way?

Example: Mocha

describe('app store validation', function(){
  describe('first-time customer', function() {
    // test setup
    it('should prompt for cc info', function() {
      // test assertions
    });
  });
});

Review

  • TDD and BDD
  • Gherkin
  • Behave
  • Features and steps
  • Mocha