使用rspec和factory_girl,在哪里存储需要共享的硬编码值?

发布于 2024-10-20 21:25:01 字数 151 浏览 1 评论 0原文

我在rails 3应用程序中使用rspec和factory_girl。

我现在正在 /spec/factories 中设置我的工厂,只是好奇我应该在哪里放置其他工厂需要引用的属性哈希或硬编码 ID?

我对此很陌生,因此正在寻求有关如何正确执行此操作的指导。

I am using rspec and factory_girl in a rails 3 app.

I am setting up my factories in /spec/factories right now, and just curious where I should place attribute-hashes or hard-coded ID's that other factories will need to reference?

I'm new to this so looking for guidance on how to do it correctly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她说她爱他 2024-10-27 21:25:01

Factory Girl 希望您使用关联和序列,而不是硬编码的 ID。以下示例为您提供了在 rdoc 中搜索内容的核心以及使用工厂的基础知识。您可能应该远离任何硬编码的 ID,因为它会导致脆弱的测试,这些测试在某些随机情况下不起作用(这需要您半天的时间才能弄清楚)。

#the basics
Factory.define(:post) do |f|
  f.association :author
end

Factory.define(:comment) do |f|
  f.text "boo"
end

# callbacks
Factory.define :article_with_comment, :parent => :article do |article|
  article.after_create { |a| Factory(:comment, :article => a) }
end

p = Factory(:article_with_comment)
p.comments.first.text # => "boo"
p.author #=> yep, used the association to make it

#sequences
Factory.define(:author) do |f|
  f.email { Factory.next(:email) }
end

# and override the default behavior
p = Factory(:post, :title => 'new post', :author => Factory(:author, :email => "[email protected]") )
p.author.email # => [email protected]

...deep inside a test

p = Post.find_by_title('new post') # => this is the most basic way to get around id's

这里还有一些更好的信息: http://robots.thoughtbot.com /post/254496652/aint-no-calla-back-girl

Factory Girl is expecting that you use associations and sequences, not hard coded id's. the following examples give you the core of what to search for in the rdoc and basics for using the factories. You should probably stay away from any hard coded id's because it will lead to brittle tests that don't work on some random occasion (which takes you half a day to get to the bottom of).

#the basics
Factory.define(:post) do |f|
  f.association :author
end

Factory.define(:comment) do |f|
  f.text "boo"
end

# callbacks
Factory.define :article_with_comment, :parent => :article do |article|
  article.after_create { |a| Factory(:comment, :article => a) }
end

p = Factory(:article_with_comment)
p.comments.first.text # => "boo"
p.author #=> yep, used the association to make it

#sequences
Factory.define(:author) do |f|
  f.email { Factory.next(:email) }
end

# and override the default behavior
p = Factory(:post, :title => 'new post', :author => Factory(:author, :email => "[email protected]") )
p.author.email # => [email protected]

...deep inside a test

p = Post.find_by_title('new post') # => this is the most basic way to get around id's

some more nice info here: http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文