Skip to content

Instantly share code, notes, and snippets.

@ichi
Last active August 23, 2016 11:51
Show Gist options
  • Save ichi/01178e4c67391f6c5a079c0994540662 to your computer and use it in GitHub Desktop.
Save ichi/01178e4c67391f6c5a079c0994540662 to your computer and use it in GitHub Desktop.
associationのidもattributesにほしいときに
# spec/support/factory_girl.rb
module FactoryGirl
module Strategy
class AttributesWithForeignKey
def association(runner)
runner.run
end
def result(evaluation)
instance = evaluation.object
assocs = instance.class.reflect_on_all_associations(:belongs_to)
assoc_attrs = assocs.map do |assoc|
fk = assoc.foreign_key
[fk, instance.send(fk)]
end.to_h
evaluation.hash.merge(assoc_attrs)
end
end
end
end
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.before :suite do
FactoryGirl.reload
FactoryGirl.register_strategy(:attributes_with_foreign_key, FactoryGirl::Strategy::AttributesWithForeignKey)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment