Using doubles to improve Student Tests
I am still very much enjoying the Makers pre-course and am also exploring Classes and Test Driven Development. I wanted to make my next task relevant to the Makers experience and so decided to build a classroom class. My first step was to cd into the projects folder on my user directory. I then made a directory called rspec-classroom to keep the practice files. My next step was to put the command bundle init in order to generate a default Gemfile in my working directory. I opened atom using the dot (.) as this opens all files in the directory in my favourite IDE (Atom!).
I then changed my gem file so that I could access rspec:
In my classroom_spec.rb file I then required spec_helper and classroom. The spec helper aids the spec test file (everything with _spec at the end is a spec file) to access the original code to be tested (held in classroom.rb). I then also wrote require “classroom” to ensure that the _spec file was able to access the classroom.rb file. After this it was important to run bundle install. This meant that everything that I had written in my gemfile would be installed so that I could test effectively. Although not best practice I decided to write my Classroom class before testing:
As you can see, I included an attribute reader for students so that the class could access the information inputted regarding students as a parameter. I then included an initialize method to ensure that the class was able to read the input of students. My next task was to build a method called list_students_names in order to go over every element of the students array and join them into a single string list separated by commas. Now the challenge was to build a test which would allow us to test the class in a controlled way. This called for the use of doubles:
I included the basics of the test structure (describe Classroom do …. end) and then the specific test that I wanted to check (it “should list student names” do … end). The challenge now was to ensure that the test could check whether the Classroom class worked according to specific criteria. My first task was to create variables within the test (student1 and student2) using double. I then used the allow syntax to ensure that the test worked within limited parameters. I then called a new Classroom class and finally returned to the actual test that I wanted to check. In this process I followed the 3 steps of: 1. Arrange (in this part of the test you set up the situation so that the test is possible), 2. Act (call the class or method), 3. Assert (in this section you check what you originally wanted to check). Finally, I ran this test in rspec using “rspec” and the test ran with 1 example and 0 failures. Test Driven Development is clearly a powerful tool for developing well balanced effective code and I am looking forward to working further on this very satisfying system for Web Development.