Basic Factory Creation
Learn to create a factory and run the factory.
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#new
orActiveRecord#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 rewrite it as follows:
Get hands-on with 1400+ tech skills courses.