2016-02-23 78 views
1

我想生成屬於:topic:group:stake工廠。 :topic應該屬於:group(如:owner_group),在這種情況下它應該是相同的:group(因爲一個:stake屬於)。主題也屬於:membership。總之,我想這對建立有效對象:ActiveRecord :: RecordInvalid:FactoryGirl的驗證失敗

it 'should set up all the factories' do 
    member = FactoryGirl.create(:membership) 
    topic = FactoryGirl.create(:topic, owner_group: member.group, membership: member) 
    stake = FactoryGirl.create(:stake, group: member.group, topic: topic) 
end 

但我得到的錯誤:

Failure/Error: stake = FactoryGirl.create(:stake, group: member.group, topic: topic) ActiveRecord::RecordInvalid: Validation failed: Group has already been taken

這裏是我的工廠:

factory :user 
    sequence(:email) { |n| "foo#{n}@bar.com" } 
end 

factory :group 
    name Faker::Company.name 

    factory :owner_group 
    end 
end 

factory :membership 
    user 
    group 
end 

factory :topic 
    owner_group 
    membership 
end 

factory :stake 
    group 
    topic 
end 

topic.rb有本協會:

belongs_to :owner_group, class_name: "Group", foreign_key: "group_id" 

我已經修復了過去的類似錯誤rake db:test:準備,這不起作用。我還用database_cleaner gem配置了spec_helper.rb。所以我懷疑這是我建立工廠的方式。

有沒有在我的工廠協會或我創造的對象造成這個錯誤的方式?

回答

1

所以它聽起來像已經有一個StakeGroup相同。我沒有看到工廠定義的問題。我會檢查你的測試數據庫,以確保stakes表是空的,但這可能不是問題。您是否有before區塊創建Stake?或者TopicGroup有一個after_create回調,會自動創建一個初始的Stake

+0

我有一個after_create的主題,使股份。非常感謝你,這讓我瘋狂。 – eeeeeean