Basic Factory Creation

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:

  1. The build(:project) method returns a model instance that has not been saved to the database.

  2. The create(:project) method returns a model instance and saves it to the database.

  3. The attributes_for(:project) returns a hash of all the factory attributes that are suitable for passing to ActiveRecord#new or ActiveRecord#create. This method is most often useful for creating a hash sent as params to a controller test.

  4. The build_stubbed(:project) is almost magical. Like build, it returns an unsaved model object. Unlike build, it assigns a fake ActiveRecord ID to the model and stubs out database-interaction methods (like save) 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 1200+ tech skills courses.