RSpec is an awesome tool for behaviour-driven testing. It’s mostly used in test driven development (“TDD”), where the developer writes the test based on what the application should do, and then creates the program to accomplish the goals of the test.
At first, I found this tedious because it means extra work for me (the developer). But in the long run, it actually saves time in the process because I can easily tell whether the program is functioning properly.
There are many types of specs but for Rails to support functions, the specs need to have the corresponding metadata :type value:
- Model specs:
- Controller specs:
- Request specs:
- Feature specs:
- View specs:
- Helper specs:
- Mailer specs:
- Routing specs:
I haven’t tried doing Mailer and Routing specs but among the other types, Feature specs testing is my favorite because it simulates the application externally via the web pages. It’s like automating the user experience and it feels like magic because the web browser is moving on its own. Because of the “real user” interaction magic, feature specs require a special gem called Capybara.
Sample RSpec test file:
Sample Factory file:
Another cool thing about this whole RSpec thingy is the Factory concept. Factories produce dummy data for tests. In my sample file, FactoryGirl is used. It basically just sets up test data but it creates Ruby objects as test data.
These are just basic tests that I can show but I’m sure I can do much more with it.
Although making tests requires additional time and effort, it’s a very good practice that will help devs maintain codes long-term. Plus, you won’t notice its “burden” because creating RSpec adventures are really enjoyable.