KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
This question is an extension to the one raised here: Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors The answer offered has worked perfectly for me. Here's what it looks like: # 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 The issue that has come up for me is when I need to manually build an association to support a polymorphic association with a uniqueness constraint in a hook. For example: 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 My current singleton implementation doesn't support ca
Tags (comma-separated)
Save Edits
Cancel