ruby-on-rails – FactoryGirl创建多个记录
发布时间:2020-12-17 03:56:09 所属栏目:百科 来源:网络整理
导读:我试图养成编写规范的习惯,然而,这变得越来越令人沮丧. 假设我有两个简单的模型:用户和故事.每个模型使用belongs_to关系.每个模型使用一个验证:foo_id,presence:true. 但是,FactoryGirl正在创建多个记录. FactoryGirl.define do factory :user do email "
我试图养成编写规范的习惯,然而,这变得越来越令人沮丧.
假设我有两个简单的模型:用户和故事.每个模型使用belongs_to关系.每个模型使用一个验证: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 我在这里错过了什么?我不能在没有用户的情况下建立一个Story工厂,但我需要它只是一个用户记录. 解决方法
只有在create或build调用中未指定值时,才会使用为工厂中的每个属性定义的值.
user = FactoryGirl.create(:user) story = FactoryGirl.create(:story,user: user) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |