ruby-on-rails - 進め方 - rails テスト 書き方
shoulda matcherを使って一意性検証テストをパスできない (2)
そのmatcher のドキュメントは次のように述べています:
このマッチャーは、他のマッチャーと少し違って動作します。 前述のように、モデルが存在しない場合は、モデルのインスタンスが作成されます。 時には、この手順は失敗します。特に、一意の属性以外の属性にデータベースレベルの制限がある場合は、この手順は失敗します。 この場合、
validate_uniqueness_of
を呼び出す前にこれらの属性を設定するという解決策があります。
したがって、あなたの場合、ソリューションは次のようになります。
describe "uniqueness" do
subject { AvatarPart.new(name: "something", type: "something else") }
it { should validate_uniqueness_of(:name).case_insensitive }
end
私はavatar_parts_spec.rbにshoulda matcherを持っており、私はそれをパスすることはできません:
テスト:
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 : https://github.com/preciz/avatar_parts
上に加えて、それを解決するために私が使用したパターン:
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