简体   繁体   中英

Factory_Girl & CanCan: Avoiding uniqueness errors

I have a rails app with a CanCan 'role' model. Role has a "name" field, which cancan calls to determine a user's permission levels.

In Factory Girl I have a whole lot of models that associate with the 'Role' field; some many iterations deep. Eg: (The 'account' factory has an association with the 'purchase' factory, which has an association with the 'user' factory, which has an association with 'role')

The problem is, if I call two factories that end up associating with 'role', the second one called will fail uniqueness validation on that role-->'name' field. Normally uniqueness validations aren't an issue - I just set the problematic attribute to a sequence...but I can't do that here - the name of the role has to be specific for the sake of cancan functionality.

So...how do I get around this?

Can you create all the roles up front and then just look them up as needed in the test?

If not, can you create the role you need in that specific test, and then pass it into the Factory?

admin_role = Factory.create(:role, :role_name => "administrator")
Factory.create(:user, :login => "joe",  :role => admin_role)
Factory.create(:user, :login => "jane", :role => admin_role)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM