Create Valid Instances of the Model Using Factory Bot
Explore creating valid and testable model instances in Rails using Factory Bot and Faker. Understand how to define factories that produce consistent, valid data, manage associations, and avoid common testing pitfalls for reliable test suites.
We'll cover the following...
Utilizing factory bot and faker in Rails
Although it’s not a test of our model, creating a model should also involve ensuring there is a way for others to create valid and reasonable instances of the model for other tests. Rails provides a test fixture facility.
Factory Bot is a library to create factories. Factories can be used to create instances of objects more expediently than using new. This is because a factory often sets default values for each field. So, if we want a reasonable Widget instance but don’t care about the values for each attribute, the factory will set them for us. This allows code like so:
widget = FactoryBot.create(:widget)
If we need to specify certain values, create acts very much like new or create on an Active Record:
widget = FactoryBot.create(:widget, name: "Stembolt")
A factory can also create any needed associated objects, so the above invocations will create (assuming we’ve written our factories properly) a manufacturer with an address as well as a widget status.
To generate dummy values, we like to use example<span>.com, we can write Faker::Internet.safe_email.
While Faker does introduce random behavior to our tests, we view this as a feature. It ...