The classic approach is to write code and then write a test for it. This often leads to tests being neglected.
Behavior Driven Development (BDD) tries to solve this problem and helps you to avoid bugs. Tests are being written as actual user-stories rather than just code with BDD. This leads to valuable, well-defined specifications of the system’s intended behavior.
Learn to take advantage of BDD by using tools like Cucumber and RSpec.