Rspec - 通过 has_many 测试唯一性

Rspec - Testing uniqueness on a has_many through

我正在尝试测试模型是否可以有多个值但不能有重复值。

我有以下型号:学校、标签、school_tag。一个学校可以有多个标签,一个标签可以属于多个学校。示例标记,'Art'、'Science'、'Math' 等

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

我目前的测试如下。它首先添加一些有效标签,然后尝试添加已添加到该集合的标签。

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

失败的部分在这里:

expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)

这是我返回的错误:

Failure/Error: expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)
     ActiveRecord::RecordInvalid:
       Validation failed: Schooltype has already been assigned

和使用<<有关系吗?我将如何进行测试?

答案: 除了下面选择的答案外,这里还引用了另一个问题来解释为什么会发生这种情况

When to use curly braces vs parenthesis in expect Rspec method?

expect with raise 应该被包裹在一个块中

expect(@school.tags << @tag1).to raise_error(ActiveRecord::RecordInvalid)

应该是

expect{@school.tags << @tag1}.to raise_error(ActiveRecord::RecordInvalid)