【问题标题】:FactoryGirl creating multiple recordsFactoryGirl 创建多条记录
【发布时间】:2014-07-04 03:10:15
【问题描述】:

我正在努力养成编写规范的习惯,但是,这变得越来越令人沮丧。

假设我有两个简单的模型:User 和 Story。每个模型都使用belongs_to 关系。每个模型也使用validates :foo_id, presence: true。

但是,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

这个简单的测试失败了:

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

我在这里缺少什么?如果没有User,我无法建立Story 工厂,但我需要它只是一个User 记录。

【问题讨论】:

  • 也显示失败的测试报告..

标签: ruby-on-rails ruby rspec factory-bot


【解决方案1】:

仅当您未在 create 或 build 调用中指定值时,才会使用您为工厂中的每个属性定义的值。

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

【讨论】:

  • 感谢您的回答。事后看来,现在似乎很清楚了。
【解决方案2】:

当你做这样的事情时,你可以这样做:

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

或者也许你只能让故事变幻莫测:

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

【讨论】:

    【解决方案3】:

    是的,在创建故事时创建关联用户是工厂女孩的一项功能。

    你可以这样避免:

    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,但你明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2016-08-20
      相关资源
      最近更新 更多