I have a rails 4 app with a Post model and a Tag model. Those models are related by an HABTM relation.
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
...
end
The Post model has an "image" column and validates its correctness trough a format validation still allowing blank.
validates :image,
format: { with: /\Ahttps\:\/\/s3.*amazonaws\.com.*\.png\z/ , message: 'Must be a valid url within S3 bucket' },
allow_blank: true
I need to add a validation that doesn't allow Post.image to be blank if a particular tag is selected. For example if Tag.name == "foo" is associated to this post, then Post.image cannot be blank.
This is the model spec that should pass:
it 'should not allow a post with tag name "foo" to have an empty image' do
mytags = [create(:tag, name: 'foo')]
expect(build(:post, image: '', tags: mytags)).to_not be_valid
end
What validation would make my test pass?