Home » Ruby Tutorial Box » TDD & BDD Best Practices with RSpec in Creating Web Service

TDD & BDD Best Practices with RSpec in Creating Web Service

TDD Process

Hi everyone, I think that many of you have heard about TDD, BDD. Although you may appreciate this process of software development, you may not have opportunity to work with the process. Today, I want to give you an overview of TDD, and a tool called RSpec for behavior testing in Ruby. Let’s start!

I. Overview

1. TDD

TDD stands for ‘Test-driven development’, a software development process in which we repeat the cycle: Write test first → Code → Refactoring through the life time of project.

2. BDD

TDD stands for ‘Behavior-driven development’ which bases on the core concept of TDD. You write unit tests, acceptance tests, integration tests, etc to check how your application behaves with requirements. However, you must do the same process as TDD. Thus, there’s no clearly difference between TDD an BDD. Writing correct tests in TDD means you are following the BDD. Reversely, doing right BDD means you are doing TDD.

You can find so many results of the two concepts on Internet, in fact, they are the same. It is an efficient process of developing a software, to have a clearly understanding of requirements, good designs, and minimal bugs. Write tests first, then code, then refactoring.


Spec is a testing tool for Ruby programming language. RSpec is created under purpose of creating products in BDD process.

RSpec provides:

  • Rich terminal commands
  • Automation testing

  • Textual descriptions which is almost the same with how people think

4. Benefits

  • Understand more clearly about requirements
  • Help developers improve code design
  • Focus on function, output expectations, then validations
  • Reduce significantly bugs
  • Ensure functions are connected together in the right way (by integration test)
  • Make source code more maintainable, more adaptable with changes, more flexible.
  • Create more freedom for developers to improve source code, change requirements, merge with other features …

II. Practical RSpec in creating a web service

1. Describe method: short and meaningful



2. Single expectation test

3. Check response format

4. Check data

5. Validate params

6. Use let & subject

7. Create data when needed

8. DRY: shared examples

9. Use FactoryGirl

10. Integration Test

11. Code Coverage (Ex: simplecov for Ruby application)

Code coverage with simple-cov

Code coverage with simple-cov

Tagged width:, ,