Ruby on rails Can';无法通过shoulda matcher的唯一性验证测试
我的阿凡达零件规格rb中有一个shoulda matcher,但我无法通过: 测试: 型号:Ruby on rails Can';无法通过shoulda matcher的唯一性验证测试,ruby-on-rails,ruby,ruby-on-rails-3,sqlite,shoulda,Ruby On Rails,Ruby,Ruby On Rails 3,Sqlite,Shoulda,我的阿凡达零件规格rb中有一个shoulda matcher,但我无法通过: 测试: 型号: 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,
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
错误的原因可能是什么
编辑:
Github repo:对于那个匹配者来说:
此匹配器的工作方式与其他匹配器略有不同。如前所述,如果模型的实例不存在,它将创建模型的实例。有时,此步骤会失败,尤其是当您对任何属性(唯一属性除外)有数据库级别的限制时。在这种情况下,解决方案是在调用的validate\u university\u之前填充这些属性
因此,在您的情况下,解决方案如下:
describe "uniqueness" do
subject { AvatarPart.new(name: "something", type: "something else") }
it { should validate_uniqueness_of(:name).case_insensitive }
end
除了上面提到的,我还使用了一种模式来解决这个问题:
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
有时这似乎是必要的,有时不是。奇怪。为什么这里需要不区分大小写的?@VishalVijay在最初的问题中,它不是答案中特别重要的部分。
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 (?, ?, ?, ?, ?)
describe "uniqueness" do
subject { AvatarPart.new(name: "something", type: "something else") }
it { should validate_uniqueness_of(:name).case_insensitive }
end
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