【问题标题】:Can't get uniqueness validation test pass with shoulda matcher无法使用 shoulda 匹配器获得唯一性验证测试通过
【发布时间】:2015-01-18 17:35:32
【问题描述】:

我的 avatar_parts_spec.rb 中有一个应该匹配器,但我无法通过:

测试:

require 'rails_helper'

RSpec.describe AvatarPart, :type => :model do
  it { should validate_presence_of(:name) }
  it { should validate_presence_of(:type) }
  it { should validate_uniqueness_of(:name).case_insensitive }
  it { should belong_to(:avatar) }
end

型号:

class AvatarPart < ActiveRecord::Base
  attr_accessible :name, :type, :avatar_id

  belongs_to :avatar

  validates_uniqueness_of :name, case_sensitive: false
  validates :name, :type, presence: true, allow_blank: false
end

迁移:

class CreateAvatarParts < ActiveRecord::Migration
  def change
    create_table :avatar_parts do |t|
      t.string :name, null: false
      t.string :type, null: false
      t.integer :avatar_id      

      t.timestamps
    end
  end
end

错误:

 1) AvatarPart should require unique value for name
     Failure/Error: it { should validate_uniqueness_of(:name).case_insensitive }
     ActiveRecord::StatementInvalid:
       SQLite3::ConstraintException: NOT NULL constraint failed: avatar_parts.type: INSERT INTO "avatar_parts" ("avatar_id", "created_at", "name", "type", "updated_at") VALUES (?, ?, ?, ?, ?)

错误的原因可能是什么?

编辑: Github 仓库:https://github.com/preciz/avatar_parts

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 sqlite shoulda


    【解决方案1】:

    The documentation 为那个匹配器说:

    此匹配器的工作方式与其他匹配器略有不同。如前所述,如果模型不存在,它将创建一个模型实例。有时此步骤会失败,特别是如果您对唯一属性以外的任何属性都有数据库级别的限制。在这种情况下,解决方案是在调用 validate_uniqueness_of 之前填充这些属性。

    所以在你的情况下,解决方案是这样的:

      describe "uniqueness" do
        subject { AvatarPart.new(name: "something", type: "something else") }
        it { should validate_uniqueness_of(:name).case_insensitive }
      end
    

    【讨论】:

    • 有时这似乎需要,有时不需要。奇怪。
    • 这里为什么需要case_insensitive
    • @VishalVijay 那是在最初的问题中,它不是答案的特别实质性的部分。
    【解决方案2】:

    除了上述之外,我使用的一种模式可以解决它:

    RSpec.describe AvatarPart, :type => :model
      describe 'validations' do
        let!(:avatar_part) { create(:avatar_part) }
    
        it { should validate_uniqueness_of(:some_attribute) }
        it { should validate_uniqueness_of(:other_attribute) }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 2012-11-28
      相关资源
      最近更新 更多