#Programming #Ruby #WebDevelopment 
# Learned Lessons
## Using `after(:create)` vs. `after(:build)`
If you add a trait that augments a hash inside an object generated with FactoryBot like so:
```ruby
FactoryBot.define do
	factory :employee do
		employer
		name { "Jake Peralta" }
		attributes {
			{
				"sense_of_humor": "childish"
			}
		}
	
		trait :married do
			after(:create) do
				attributes["spouse"] = "Amy Santiago"
			end
		end
	end
end
```
When unit testing with a parent object like so (assume the underlying models exist and that an employer has many employees):
```ruby
employer = create(:brooklyn_99th_precinct)
jake = create(:employee, :married, employer: employer)
```
If you call `employer.employee.first.attributes` at this point, you might be surprised at the result:
```json
{
	"sense_of_humor": "childish"
}
```
If this happens to you, it's because you used the wrong hook. You should be using:
```ruby
		trait :married do
			after(:build) do
				attributes["spouse"] = "Amy Santiago"
			end
		end
```
Now you will see:
```json
{
	"sense_of_humor": "childish",
	"spouse": "Amy Santiago"
}
```
This is because the `after(:build)` hook occurs before persistence, whereas `after(:create)` happens *after* persistence. If you are constrained to use the `after(:create)` hook, then make sure to explicitly persist the object after it is created by the factory:
```ruby
jake.save!
```