Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unclear when to use a specific FactoryGirl syntax

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.

like image 936
IAmNaN Avatar asked Apr 27 '12 22:04

IAmNaN


2 Answers

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.

like image 111
IAmNaN Avatar answered Nov 12 '22 23:11

IAmNaN


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
like image 38
Salil Avatar answered Nov 12 '22 22:11

Salil