Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Girl Newbie: How to create new record only if doesn't already exist

Is there a simple way in factory girl to create a new factory only if one doesn't already exist?

If there isn't a simple way, what's the most concise means to ensure only one factory is created for a set of cucumber features (and/or specs)?

For example, I need a single (common) administrator record in a 'user' model to test multiple cucumber features. Ideally I'd like to do it without wrapping conditionals around every create admin step, but without hitting the 'record already exists' error.

Any suggestions appreciated.

like image 816
PlankTon Avatar asked Jan 06 '11 07:01

PlankTon


2 Answers

Create a helper method to either create or return a singleton instance.

def create_or_return_admin_user
  @user ||= Factory(:user, :admin => true)
end

and then call

create_or_return_admin_user

in your test.

like image 192
Tim Harding Avatar answered Nov 05 '22 20:11

Tim Harding


You can't do that in Factory_girl only, you need to create a method checking if the record exist or if it's not in your database.

If you do that in the setup ( before Rspec ) you can be sure that there is only one record.

like image 20
shingara Avatar answered Nov 05 '22 21:11

shingara