Test Driven Development with Rspec

After graduating from Flatiron School’s Software Engineering Bootcamp, the first topic I wanted to dive into was testing and test driven development. Throughout the course, we used tests to guide us to write the correct code and solve the problem. The tests were already written for us though. Now I wanted to learn how to write and implement my own tests.

I started by focusing on a Rails Application I was working on and to my surprise the Rspec-rails gem was much easier to use than I anticipated. First I removed all of the test files that came with generating resources in my app. Then I included the gem ‘rspec-rails’ in my gem file and ran Bundle Install. The next step was to run the command rails generate rspec:install which created the basic set up for me to use Rspec tests.

Under the new spec folder created, I organized my testing files by MVC so I created a folder for Models, Views and Controllers, each containing test files related to that specific class. The first test I created was for the Items. Each item had an attribute of color and description, but I wanted to created a method that would combine the two in a string format since I would be combining the two attributes often.

First you describe what you are working with (in this case Item of the model type). describe Item, type: :model do

Then you describe the method (in this case, the instance method I wanted to call full_description). describe “#full_description” do

From there I create a specific example of an Item to use as the test case (giving it a color and description).
let(:item) { Item.create(color: “blue”, description: ‘cap’) }

Then you code what you expect the result of this method to be (in this case I want the color and description).
it “returns ‘blue cap’” do
expect(item.full_description).to eq(item.color + “ “ + item.description)

So my complete test looked like this:

Once I had the test written, I knew exactly how to follow the errors and create the method I wanted because I had done that in bootcamp a million times! I really like the idea of test driven development because it makes you sit down and think about what you really want to accomplish before you code it. Once you write the test you have a much clearer path to your solution.

Test Test Test!

I am 34 years old and making a huge career change by attending Flatiron School’s Software Engineering Bootcamp. Excited to learn!