Skip to content

Instantly share code, notes, and snippets.

@fespinoza
Created June 2, 2014 06:51
Show Gist options
  • Save fespinoza/9558cb444b41ca2b3b0e to your computer and use it in GitHub Desktop.
Save fespinoza/9558cb444b41ca2b3b0e to your computer and use it in GitHub Desktop.
HABTM relation validation
class Variant < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :variants
end
# specs
require 'spec_helper'
describe Post, :wip do
describe '#validate_variant' do
it 'adds errors if the post doen\'t have at least a variant' do
post = build(:post)
post.valid?
expect(post.errors[:variant_ids]).to be_present
end
it 'returns true when the post have at least one variant', :now do
variant = create(:variant)
post = variant.posts.build(attributes_for(:post))
post.valid?
expect(post.errors[:variant_ids]).to be_empty
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment