我试图养成编写规范的习惯,然而,这变得越来越令人沮丧.
假设我有两个简单的模型:用户和故事.每个模型使用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)