gpt4 book ai didi

ruby-on-rails - 无法使用 shoulda 匹配器获得唯一性验证测试通过

转载 作者:IT王子 更新时间:2023-10-29 06:18:11 28 4
gpt4 key购买 nike

我的 avatar_parts_spec.rb 中有一个 shoulda 匹配器,但我无法让它通过:

测试:

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 repo :https://github.com/preciz/avatar_parts

最佳答案

The documentation对于那个匹配器说:

This matcher works a bit differently than other matchers. As noted before, it will create an instance of your model if one doesn't already exist. Sometimes this step fails, especially if you have database-level restrictions on any attributes other than the one which is unique. In this case, the solution is to populate these attributes with before you call validate_uniqueness_of.

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

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

关于ruby-on-rails - 无法使用 shoulda 匹配器获得唯一性验证测试通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27046691/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com