I'm trying to test that a model can have many values but not duplicate values.
I have the following models: school, tag, school_tag. A school can have many tags, and a tag can belong to many schools. An example tag, 'Art', 'Science', 'Math', etc.
class School
has_many :school_tags, dependent: :destroy
has_many :tags, through: :school_tags
end
class Tag
has_many :school_tags, dependent: :destroy
has_many :schools, through: :school_tags
end
class SchoolTag < ActiveRecord::Base
belongs_to :tag, foreign_key: 'tag_id'
belongs_to :school, foreign_key: 'school_id'
validates_uniqueness_of :tag_id, scope: :school_id, message: 'has already been assigned to this school'
end
My current test is below. It adds some valid tags first, but then tries to add a tag that's already been added to that collection.
before(:each) do
@school = FactoryGirl.create(:school)
@tag1 = FactoryGirl.create(:tag) #creates "Test1"
@tag2 = FactoryGirl.create(:tag) #creates "Test2"
end
it 'can have multiple tags but not duplicates' do
@school.tags << @tag1
@school.tags << @tag2
expect(@school.save).to be(true) #works
expect(@school.tags.count).to eq(2) #works
#FAILS
expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)
expect(@school.tags.count).to eq(2)
end
The part where it fails is here:
expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)
This is the error I get back:
Failure/Error: expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)
ActiveRecord::RecordInvalid:
Validation failed: Schooltype has already been assigned
Does it have anything to do with using <<
? How would I go about testing this?
ANSWER: Aside from the selected answer below, here is a reference to another question explaining why this happens
When to use curly braces vs parenthesis in expect Rspec method?