Challenge 2: A FactoryBot Factory — Solution # spec/factories/posts.rb FactoryBot.define do factory :post do title { "A perfectly reasonable title" } body { "Some perfectly reasonable body text." } association :user end end # in a spec: post = create(:post, title: "Overriding just the title") post.title # => "Overriding just the title" post.body # => "Some perfectly reasonable body text." (factory default, untouched) post.user # => an automatically-created User record =begin Notes: - association :user tells FactoryBot to create a real User record (via a :user factory defined elsewhere) and assign it, rather than leaving user_id nil -- without this, saving the post would fail belongs_to's implicit presence validation (rails1-7). - create(:post, title: "...") only overrides the title attribute passed in; every other attribute -- body, the user association -- falls back to whatever the factory defines by default. - Using { } (a block) rather than a plain string for title and body means FactoryBot evaluates it fresh for every record created, avoiding all created posts sharing the exact same in-memory string object. - create saves to the test database; build (not used here) would construct the same object without persisting it, useful for specs that don't need a saved record at all. =end