Basic Factory Creation
Explore how to create and manage test objects using factory_bot in Rails testing. Understand different build strategies such as build, create, attributes_for, and build_stubbed to optimize test data setup, and learn how to customize and associate factories effectively.
The factory_bot provides four ways of turning a factory into a Ruby object. For the project factory we were looking at, the four ways are as follows:
-
The
build(:project)method returns a model instance that has not been saved to the database. -
The
create(:project)method returns a model instance and saves it to the database. -
The
attributes_for(:project)returns a hash of all the factory attributes that are suitable for passing toActiveRecord#neworActiveRecord#create. This method is most often useful for creating a hash sent as params to a controller test. -
The
build_stubbed(:project)is almost magical. Likebuild, it returns an unsaved model object. Unlikebuild, it assigns a fake ActiveRecord ID to the model and stubs out database-interaction methods (likesave) such that the test raises an exception if they are called.
The existing project_spec uses basic Project and Task instances. We can ...