2

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?

PlankTon
  • 12,443
  • 16
  • 84
  • 153

1 Answers1

1

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)
BBonifield
  • 4,983
  • 19
  • 36
jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • Cheers for the reply. Potentially yes, but a lot of the factories are deeply nested. So if, for example, I wanted to create an 'enrolment' factory, I'd have to create a role factory, then a user factory with the role set, then a purchase factory with the user set, then an enrolment with that purchase set. – PlankTon Oct 17 '11 at 21:50
  • Hm, what if you had a list of roles, and when a role is created it `.pop` it off the list? Or what if you just write a method (not a factory) in your `Factories.rb` that returns a relevant role when necessary (in a factory) to prevent duplicates? – jefflunt Oct 17 '11 at 23:53
  • A solution like what is noted here ( http://stackoverflow.com/a/7213281/241232 ) would likely suit the need. The only issue is that it's up to the developer to remember to use that method when defining new factories that need roles. – BBonifield Sep 28 '12 at 16:38