作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我的 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/
我是一名优秀的程序员,十分优秀!