I create a basic Rails 5 application, add an scaffold and create some basic tests on the model. I use RSpec for the test environment, Factory Girl for the factories and Faker to generate some test data. Ready? Let’s go!.
Step 1. Prepare the basic infrastructure
I’am using RVM to keep the Rails’ versions under control, but you can use other tool to do it; the important thing here is to choose Rails 5 in your environment.
So I create the app as usual.
Then I can add the corresponding gems to Gemfile:
The next step is to install the gems, generate the basic RSpec infrastructure and create the scaffold for our Person class, the class I will use as example:
I edit the model in order to add two validations and a new method ‘identifier’ that returns a concatenated string. The validations and the method will be used later on the tests.
With this in place I migrate the database and prepare the tests. At this point I should be able to execute the test created by the scaffold (31 in total in this case).
Step 2. Add the factories
Add the factories to create valid objects to be used in the tests. To do so create the ‘people.rb’ file (note the file name ‘people’, plural of ‘person’). I also include Faker to generate fake values on the object’s attributes.
Step 3. Add the tests
I will verify the Person class has a valid factory, that it is not valid without a name and an age, and that the ‘identifier’ method returns a valid value. This shouldn’t be difficult.
Et voila! I can easily execute the test… with 0 failures!!
Is this post useful for you? Would you improve/change something? Please add a comment and explain your idea to all of us. Thanks!