‘FactoryBot’ and ‘Faker’ for Testing
Testing is the most vital part of development, without it our application will become rigid and might as well break as we add more features to it. Data is one of the requirements for a successful and complete testing, but the question is where do we get this data from? You might think of creating some imaginary data, well that is not a very good idea as we end up violating the DRY(do not repeat yourself) principle. Also if we have hundreds of test cases we cannot sit and create hundreds of imaginary data. So, the question is what do we do?
The solution to is problem is using “Data Factory”. It is a blue print that allows us to create an object or collection of objects, with predefined values. There are several tools to create a factory, one such tool is ‘FactoryBot’. Factory Bot is a useful tool that allows us to call on a pre-made object with a short snippet within our tests. Combined with Faker, which allows us to randomise the object attributes based on a large internal library, we will be able to set up each test with minimal effort, and get back to coding our app as fast as possible. Setup is a breeze, and preparation is minimal compared to the time you spend creating objects by hand in each test file.
The first step is to add ‘factory_bot_rails’ and ‘faker’ to our test group in the Gem file.
After this, make sure to bundle install so that the changes made here will take effect. Next, add the following lines in test_helper.rb file:
With everything in place now and all the settings done we can move forward with creating data. Lets take an example where we have a model named articles in our project and we have to write tests for it.
Next step is to create test/factories directory, our factory will be inside this directory.
Create a file named article.rb , factory for articles model will look like this:
Now we move on to writing some tests for articles model inside the test/models/article_test.rb directory.
Similarly we can create data for all the models in our project and successfully run tests for each model. This way we can save our time and complete testing efficiently.
I hope this blog gave you a clear idea of what FactoryBot and Faker gems are and how we can use them. You can share your views by commenting and don’t forget to give👏(claps).
Thank You.