Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

We have implemented it like this:

In Cucumber the 'background' scenario is executed before each 'scenario' in the feature file. So, in the top of each feature file (in the 'background') we setup a user and give the user the admin role.

Now this gives you an admin user ready and available in each 'scenario'.

Note that this admin user will not survive in the db from feature to feature, as Cucumber is handling records in transactions. So if you need to add something to this admin user in one feature, and use it from another feature, this way of doing it is not usable. But as I understood your question, you just want to ensure that you will not attempt to create the admin user if it is already created. Creating the admin user in the 'background' ensures that it is only created once for each feature.

Note that you could instead create the admin user in each 'scenario'. Cucumber will remove it from the db at the end of the 'scenario', so at any point you will also only have one admin user. This however is not DRY and should not be done (unless you only need the admin user in some 'scenarios', and specifically require it not to be present in other 'scenarios').

Cucumber 'background' example using FactoryGirl step definition:

Background:
  Given the following user exists:
    | Name  | Role          |
    | Admin | Administrator |

Factory definition:

factory :user do
  name 'John Doe'
  role 'Guest'
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top