【问题标题】:Rspec - Testing uniqueness on a has_many throughRspec - 通过 has_many 测试唯一性
【发布时间】:2015-09-08 22:39:11
【问题描述】:

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

我有以下模型:school、tag、school_tag。一个学校可以有很多标签,一个标签可以属于很多学校。一个示例标签,“艺术”、“科学”、“数学”等。

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

和使用&lt;&lt;有什么关系吗?我将如何进行测试?

回答: 除了下面选择的答案之外,这里是对另一个问题的参考,解释了为什么会发生这种情况

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec tdd factory-bot


    【解决方案1】:

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

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

    应该是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多