I have model Category which has and belongs to many Packages. When a user creates a Posting in a Category, it must belong to a Package that is in its category.
Here's the code for the custom validator:
class PackageValidator < ActiveModel::Validator
def validate(record)
record.errors[:package_id] <<
I18n.t('errors.messages.package.not_in_category') unless
record.category.packages.include? record.package
end
end
This works great and all, but it breaks all my rspec tests (with factory_girl) because factory_girl creates a new Package for each Category and Posting I build/create with it.
Here's my factories:
factory :category do
sequence(:name) {|n| "Parts#{n}"}
sequence(:slug) {|n| "parts#{n}"}
packages {[FactoryGirl.create(:package)]}
end
factory :posting do
title 'Foo'
body 'Bar'
category
package
end
factory :package do
sequence(:name) {|n| "Basic#{n}"
price 0
photos 5
end
How can I make it all play nicely together?
You can set the package to category.packages.first
in an after(:build)
hook.