Test Driven Development (aka TDD) is where you create test specs of expected outcomes. You can then code your way to pass these tests. The opposite of this method of coding is Behavioral Driven Development (BDD).
First thing we need to do is install the ‘rspec-rails’ gem. We want this in the development test section in our gem file.
We can then create our rspec files using
rails g rspec:install
For this example let’s pretend we have 3 models. User, Cart, and Item.
When we use:
rails g resource Model attribute:type
The rspec file will be created for that model. To manually generate the file we can use
rails g rspec:model model_name
Creating a test
Lets create a test that totals all items in a users cart. Inside the user_spec.rb
Inside the #setup we are creating test cases. Inside the #verify we have:
Coding to the Test Specs
When we run rspec we get the following error:
We can see NoMethodError for total_cart. So lets create a method for that in the User model.
We got rid of no method error, but we expected 5.0
So let’s see if can code something to pass this test spec.
After coding out the method and running rspec, we can see we passed the test!
In the above example, we used a very easy test scenario. But what if it was more complex? What if we wanted to refactor? We can always test our code against the expected outcome. We can also zero in to where our code breaks.
For more documentation on Rspec-rails check out the docs here.