Search code examples
ruby-on-railsrubyruby-on-rails-4rspecfactory-bot

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  
 end
end

And usage is straightforward:

user.save(context: :admin)

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


Solution

  • 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)