如何在 FactoryGirl 中访问传入参数的哈希值
我正在 Rails 中开发 Web 后端。我的 Article
模型主要是一个包装器,它将大多数方法委托给最新的 ArticleVersion
。不过,在编写 FactoryGirl 工厂时,我试图创建一个 :article_with_version 工厂来生成 Article
并为其提供版本,但我不确定如何从 Article< 转发参数/code> 工厂到
ArticleVersion
。
这是相关代码:
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
我希望能够做的是调用 Factory(:article_with_version, :title => "The Grid", :contents => "
Greetings,programs!< ;/h1>")
并让 FactoryGirl 将这些 :title 和 :contents 参数传递给新的 ArticleVersion
(或如果省略则为零)。有没有办法访问 Factory.create() 期间传递的动态参数的哈希值?
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()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用瞬态属性来完成此操作,如下所示:
请注意,被忽略的属性不会在文章本身上设置,尽管看起来这就是您在本例中想要的行为。
You can do it using transient attributes like this:
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.