My focus for this term has been testing the Assignment model with RSpec. The major components of this testing included:
- Migrating existing rake tests to RSpec tests,
- Adding additional tests and
- Improving the Assignment model itself (through adding additional validations, removing unused methods and improving existing methods).
I have been creating tests for the model using a unit-method approach. This is what is suggested when testing models. I created a separate describe block to test each Assignment method and only that method. Every method should have an associated describe block upon completion of the Assignment model testing. When I finish testing a method, I delete the associated tests from the rake test suite. Therefore, the old Assignment tests should also all be removed by the time all of the RSpec tests are in place. It is worth noting that there are many methods in the Assignment model without tests for them. One should not rely on simply migrating the tests to ensure good test coverage.
I realized early on that, realistically, there is a good chance no one will inspect the coverage of these tests for a long time after I’ve written them. This is why I was very thorough when testing. I focused on the methods one-at-a-time instead of thinking about the amount of work left to keep myself from just speeding through them. My boiled-down process looks something like:
- Focus on a method that is in the current test suite.
- Inspect the method to see what it does and how it does it.
- Create RSpec tests for that method.
- Ensure all tests in the old test suite have been covered and remove them.
- Commit changes.
I make changes to the method throughout the process if I see anything that could be improved.
I suggest drawing out a diagram of the associations between the models you are working with. Jumping into testing in a new codebase can be a bit daunting and drawing out a rough diagram really helped me understand how the models fit together. In addition, be sure to play around with the application to find where each model matters. It will help create a mental picture of models as you work with them.
I learned RSpec while working on the tests. Here are some useful links I’ve gathered on RSpec testing:
- http://betterspecs.org/ (best practices)
- http://robots.thoughtbot.com/how-we-test-rails-applications (tips and test types)
- https://gist.github.com/kyletcarlson/6234923 (model testing template)
- http://www.methodsandtools.com/tools/rspecbestpractices.php (more tips; realize most tips are for controller testing)
- Bonus: http://www.amazon.ca/Rails-4-Way-3rd/dp/0321944275/ref=sr_1_1?ie=UTF8&qid=1417150279&sr=8-1&keywords=the+rails+4+way (where I started learning about RSpec; a truly phenomenal Rails book)