Elmor Elmor - 8 months ago 39
Ruby Question

How to create models in context with factory_girl?

In my model, I have some context validation:

class User
validate :permissions, on :admin

def permissions
error.add(:permissions, 'Must be set as admin') unless permissions.include? :admin

And usage is straightforward:

user.save(context: :admin)

The question is: How may I check that validations are run in
context via factory_girl? E.g.
create :user, context: :admin
doesn't work.


I don't think factory_girl provides a way to create or save with that option. However, you can work around it with factory_girl's build

FactoryGirl.build(:user).save!(context: :admin)

or attributes_for:

User.create!(FactoryGirl.attributes_for(:user), context: :admin)