...

/

Create Valid Instances of the Model Using Factory Bot

Create Valid Instances of the Model Using Factory Bot

Learn to create valid instances using the factory bot in our Rails application.

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 FakerFaker is a library for generating fake data, such as names, addresses, and phone numbers.. Faker can provide random, fake values for fields of various types. For example, to create a realistic email address on a known safe-for-testing domain like example<span>.com, we can write Faker::Internet.safe_email. ...