jmchargue
jmchargue

Reputation: 179

Is there a way to override create method as well as build in factory girl?

In factory girl, you can override the build method by specifying an initialize_with block, is there a way to do this with the create method?

It looks like when you call create in factory girl, it internally calls #build, then save!. However, I am using an API/gem backed model, and calling #build then save! will not work, but it does have the concept of persistence. How should I override create for these factories? It would be a lot cleaner than overriding save!.

Upvotes: 5

Views: 2305

Answers (1)

Schwern
Schwern

Reputation: 165208

Yes, you can override to_create. See Custom Methods For Persisting Objects in GETTING_STARTED.

factory :different_orm_model do
  to_create { |instance| instance.persist! }
end

You can also define a custom "strategy", which is what FactoryGirl calls things like build and create.

Upvotes: 6

Related Questions