FactoryGirl creating multiple records

factory-bot, rspec, ruby, ruby-on-rails

Solution

The values you define for each attribute in a factory are only used if you don't specify a value in your `create` or `build` call.

user = FactoryGirl.create(:user)
story = FactoryGirl.create(:story, user: user)

Problem

I'm trying to get in the habit of writing specs, however, this is becoming increasingly frustrating. Assume I have two simple models: `User` and `Story`. Each model uses a `belongs_to` relation. Each model uses a `validates :foo_id, presence: true` as well. However, FactoryGirl is creating multiple records. ``` FactoryGirl.define do factory :user do email "foo@bar.com" password "foobarfoobar" end # this creates user_id: 1 factory :story do title "this is the title" body "this is the body" user # this creates user_id: 2 end end ``` This simple test fails: ``` require 'rails_helper' describe Story do let(:user) { FactoryGirl.create(:user) } let(:story) { FactoryGirl.create(:story) } it 'should belong to User' do story.user = user expect(story.user).to eq(user) end end ``` What am I missing here? I cannot build a `Story` factory without a `User`, yet I need it to be just one `User` record.

Original source