简体   繁体   English

FactoryGirl创建多个记录

[英]FactoryGirl creating multiple records

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 . 假设我有两个简单的模型: UserStory Each model uses a belongs_to relation. 每个模型使用belongs_to关系。 Each model uses a validates :foo_id, presence: true as well. 每个模型使用一个validates :foo_id, presence: true

However, FactoryGirl is creating multiple records. 但是,FactoryGirl正在创建多个记录。

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. 我不能在没有User情况下建立一个Story工厂,但我需要它只是一个User记录。

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. 只有在createbuild调用中未指定值时,才会使用为工厂中的每个属性定义的值。

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

Yes, it is a feature of factory girl to create the associated user when you create the story. 是的,在创建故事时创建关联用户是工厂女孩的一项功能。

You can avoid it like this: 你可以这样避免它:

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

This example is setup to be trivially true , but you get the point. 这个例子是设置为平凡true ,但你明白了吧。

When doing something like this you can do: 做这样的事情你可以这样做:

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

Or maybe you can only let the story variable and do: 或者你可以只让故事变量并做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM