Reputation: 173
I am working on a web backend in Rails. My Article
model is largely a wrapper that delegates most methods to the most recent ArticleVersion
. When writing FactoryGirl factories, though, I was trying to create an :article_with_version factory that generates an Article
and gives it a version, but I'm not sure how to forward parameters from the Article
factory on to the ArticleVersion
.
Here is the relevant code:
class Article < ActiveRecord::Base
has_many :versions, :class_name => "ArticleVersion"
def title
self.versions.last.title
end # method title
def contents
self.versions.last.contents
end # method contents
end # model Article
FactoryGirl.define do
factory :article_version do; end
factory :article do; end
factory :article_with_version, :parent => :article do
after_create do |article|
article.versions << Factory(:article_version, :article_id => article.id)
end # after_create
end # factory :article_with_version
end # FactoryGirl.define
What I would like to be able to do is call Factory(:article_with_version, :title => "The Grid", :contents => "<h1>Greetings, programs!</h1>")
and have FactoryGirl pass those :title and :contents parameters on to the new ArticleVersion
(or nil if those are omitted). Is there a way to access that hash of dynamic parameters that are passed on during Factory.create()?
Upvotes: 0
Views: 2151
Reputation: 1228
You can do it using transient attributes like this:
factory :article_with_version, :parent => :article do
ignore do
title nil
contents nil
end
after_create do |article, evaluator|
article.versions = [FactoryGirl.create(:article_version, title: evaluator.title, contents: evaluator.contents)]
article.save!
end
end
Just note that the attributes being ignored will not be set on the Article itself, although it looks like that is the behaviour you want in this case.
Upvotes: 2