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? Eg 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)
FactoryBot offers a to_create
method that can be used like this:
FactoryBot.define do
factory :user do
trait :admin do
to_create { |instance| instance.save!(context: :admin) }
end
end
end
Or without the trait
:
FactoryBot.define do
factory :user do
to_create { |instance| instance.save!(context: :admin) }
end
end
By default, creating a record will call
save!
on the instance; since this may not always be ideal, you can override that behavior by definingto_create
on the factory:
factory :different_orm_model do
to_create { |instance| instance.persist! }
end
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.