Unclear when to use a specific FactoryGirl syntax
Asked Answered
S

2

6

In the latest release of FactoryGirl, some syntactic methods such as Factory.create were depreciated in favor of several others, most notably FactoryGirl.create and the simpler create.

However, experience shows that certain syntaxes are not always appropriate given the context.

Take for example:

FactoryGirl.define do

  factory :article do
    after_create {|a| a.comments << create(:comment) }
  end

  factory :comment do
  end

end

Where Article has_many Comments, and Comments belongs_to Article. In the above factories, a.comments << create(:comment) issues the error Comment(#nnn) expected, got FactoryGirl::Declaration::Static. Change that line to a.comments << FactoryGirl.create(:comment) and the error goes away.

It is not clear when one syntax should take precedence over any other form.

Same answered 27/4, 2012 at 22:47 Comment(0)
S
5

I learned the abbreviated notation is not supported in callbacks (such as after_create) as of the current version (3.2.0). This information came directly from the FactoryGirl teams via Google groups. I'll update this question when/if it's added in a future version.

Same answered 2/5, 2012 at 7:33 Comment(2)
You're a friggin lifesaver dude. I'm just going to blanket use the long syntax. Better some extra keystrokes than hours of clueless debugging.Zonnya
I asked this a year ago, and have been using the long-form since then. Yeah, I agree, way less head scratching.Same
P
1

As per the FactoryGirl documentation, if you want to omit the FactoryGirl module prefix while calling methods like create and build, you need to mix-in FactoryGirl methods in rspec/test-unit module like this:

# rspec
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end
Penna answered 28/4, 2012 at 16:1 Comment(1)
Thanks for the reply Salil. Yes, I have done that, which allows me to use create in only the situations described above.Same

© 2022 - 2024 — McMap. All rights reserved.