FactoryGirl creates several records

I'm trying to get used to writing specifications, but this is becoming increasingly frustrating.

Suppose I have two simple models: Userand Story. Each model uses a relationship belongs_to. Each model also uses validates :foo_id, presence: true.

However, FactoryGirl creates a few entries.

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 Storyfactory without User, but I need this to be only one entry User.

+4
source share
3 answers

, factory, , create build.

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

, factory .

:

require 'rails_helper'

describe Story do
  let(:story) { FactoryGirl.create(:story) }
  let(:user) { story.user }

  it 'should belong to User' do
    story.user.should eq user
  end
end

- true, .

+1

When you do something like this, you can do:

let(:story) { FactoryGirl.create(:story, user: user) }

Or maybe you can only enable the story variable and do:

let(:story) { FactoryGirl.create(:story, user: user) }
let(:user)  { User.last}
+1
source

Source: https://habr.com/ru/post/1547100/


All Articles