Question

I have two factories (post_factory.rb, comment_factory.rb) in separate files. I'd like to create a bit complex factory, which will create a post with associated comments for me. I created a third file, called complex_factory.rb, and wrote the following code:

Factory.define :post_with_comments, :parent => :post do |post|
  post.after_create { |p| Factory(:comment, :post => p) }
end

But rake spec raises an error, stating that the file is unaware of post and comment factories. At the very next moment, I naïvely wrote requires at the top:

require "post_factory.rb"
require "comment_factory.rb"

But that didn't gave any proper result. Maybe this requires actually looking the wrong direction? Or they pretty much don't matter (as registering factories for visibility might be more complex that I assume).

Am I missing something? Any ideas?

Was it helpful?

Solution

Actually i've figured out that files with factories see each other. If we have a comment_factory.rb alongside with post_factory.rb, this following code will work fine (post factory):

Factory.define :post_with_comments do |post|
  post.caption = "Caption"
  post.body "Some dummy text"
  post.after_create { |p| Factory(:comment, :post => p) }
end

While comment_factory.rb looks as following:

Factory.define :comment do |comment|
  comment.body "Some wise comment text"
  comment.post_id
end

OTHER TIPS

The require you added doesn't work because it doesn't have the proper path prefix.

However, factory_girl should be doing this for you automatically. See the README in the git repository. It says:

Factories can either be defined anywhere, but will automatically be loaded if they are defined in files at the following locations:

test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb

You must have your factories outside the default location. If you can't just move them to the default, then use something like this:

Dir[File.expand_path(File.dirname(__FILE__)) + "/factories/*.rb"].each do |file|
    require file
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top