【发布时间】:2012-03-29 12:27:49
【问题描述】:
这个问题是对这里提出的问题的扩展:
Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors
提供的答案对我来说非常有效。这是它的样子:
# Creates a class variable for factories that should be only created once.
module FactoryGirl
class Singleton
@@singletons = {}
def self.execute(factory_key)
begin
@@singletons[factory_key] = FactoryGirl.create(factory_key)
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
# already in DB so return nil
end
@@singletons[factory_key]
end
end
end
我遇到的问题是当我需要手动构建关联以支持具有唯一性约束的多态关联时。例如:
class Matchup < ActiveRecord::Base
belongs_to :event
belongs_to :matchupable, :polymorphic => true
validates :event_id, :uniqueness => { :scope => [:matchupable_id, :matchupable_type] }
end
class BaseballMatchup < ActiveRecord::Base
has_one :matchup, :as => :matchupable
end
FactoryGirl.define do
factory :matchup do
event { FactoryGirl::Singleton.execute(:event) }
matchupable { FactoryGirl::Singleton.execute(:baseball_matchup) }
home_team_record '10-5'
away_team_record '9-6'
end
factory :baseball_matchup do
home_pitcher 'Joe Bloe'
home_pitcher_record '21-0'
home_pitcher_era 1.92
home_pitcher_arm 'R'
away_pitcher 'Jack John'
away_pitcher_record '0-21'
away_pitcher_era 9.92
away_pitcher_arm 'R'
after_build do |bm|
bm.matchup = Factory.create(:matchup, :matchupable => bm)
end
end
end
我目前的单例实现不支持调用FactoryGirl::Singleton.execute(:matchup, :matchupable => bm),只支持FactoryGirl::Singleton.execute(:matchup)。
您如何建议修改单例工厂以支持诸如FactoryGirl::Singleton.execute(:matchup, :matchupable => bm) 或FactoryGirl::Singleton.execute(:matchup) 之类的调用?
因为现在,上面的代码每次在 factory :baseball_matchup 上运行钩子时都会抛出唯一性验证错误(“事件已被接受”)。最终,这是需要修复的,所以数据库中不超过一场比赛或棒球比赛。
【问题讨论】:
标签: ruby rspec singleton factory-bot