2014-11-20 3 views
11

Ho un matcher shoulda nel mio avatar_parts_spec.rb e non riesco a passare:Non è possibile ottenere l'unicità passaggio test di convalida con shoulda matcher

prova:

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 

Modello:

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 

migrazione:

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 

Errore:

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 (?, ?, ?, ?, ?) 

Quale potrebbe essere la causa dell'errore?

Edit: Github repo: https://github.com/preciz/avatar_parts

risposta

29

The documentation per quella matcher dice:

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 .

Quindi nel tuo caso la soluzione sarebbe qualcosa di simile:

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

A volte questo sembra essere necessario, a volte no. Strano. –

+0

Perché qui è richiesto "case_insensitive"? –

+3

@VishalVijay Questo era nella domanda originale, non è una parte particolarmente significativa della risposta. –

0

Inoltre sopra, uno schema che ho usato che lo risolve:

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