2016-01-13 111 views
0

我有Referral跟蹤推介的模型(即當社交媒體網站上的用戶生成唯一的推薦/邀請鏈接並邀請其他人加入應用時)。Shoulda Matchers嘗試在驗證唯一性時插入`nil`值

  • Referr - 一個誰發出自己獨特的邀請鏈接
  • Referr EE - 一個誰接收和使用該鏈接註冊

我的模型和規格的佈局如下

型號

# app/models/referral.rb 

class Referral < ActiveRecord::Base 
    # A referral has one user who refers and one user who is being referred. Both are User models. 
    belongs_to :referrer, class_name: "User", foreign_key: "referrer_id" 
    belongs_to :referree, class_name: "User", foreign_key: "referree_id" 

    # Validate presence - don't allow nil 
    validates :referrer_id, presence: true 
    validates :referree_id, presence: true 

    # Referrers can have multiple entries, must be unique to a referree, since they can 
    # only refer someone once. 
    # Referees can only BE referred once overall, so must be globally unique 
    validates :referrer_id, uniqueness: { scope: :referree_id } 
    validates :referree_id, uniqueness: true 
end 

規格

# spec/models/referral_spec.rb 
require "spec_helper" 

RSpec.describe Referral, type: :model do 
    describe "Associations" do 
    it { should belong_to(:referrer) } 
    it { should belong_to(:referree) } 
    end 

    describe "Validations" do 
    it { should validate_presence_of(:referrer_id) } 
    it { should validate_presence_of(:referree_id) } 

    it { should_not allow_value(nil).for(:referrer_id) } 
    it { should_not allow_value(nil).for(:referree_id) } 

    # These two FAIL 
    it { should validate_uniqueness_of(:referrer_id).scoped_to(:referree_id) } 
    it { should validate_uniqueness_of(:referree_id) } 
    end 
end 

我的問題是,最後兩個規範測試總是失敗,像

1) Referral Validations should require case sensitive unique value for referrer_id scoped to referree_id 
    Failure/Error: it { should validate_uniqueness_of(:referrer_id).scoped_to(:referree_id) } 
    ActiveRecord::StatementInvalid: 
    PG::NotNullViolation: ERROR: null value in column "referree_id" violates not-null constraint 
    DETAIL: Failing row contains (1, 2016-01-13 19:28:15.552112, 2016-01-13 19:28:15.552112, 0, null). 
    : INSERT INTO "referrals" ("referrer_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" 

它看起來像shoulda匹配器正試圖在插入nil值在那裏測試各種價值。玩allow_niltruefalse沒有解決它。

任何想法爲什麼它可能會在那裏磕磕絆絆?

謝謝!

回答

1

看看一個不存在this

validate_uniqueness_of匹配創建一個新的實例。雖然這樣做,但由於某些其他領域的模型驗證可能會失敗。在你的情況下,雖然驗證referrer_id的唯一性,但refertt_id的值爲零,因此失敗。

解決方案是創建一個實例並將值分配給在列中引發ERROR:null值的屬性。

再次參考第一行中的鏈接例子和詳細說明

+0

完美!這是確切的問題,謝謝:)對於我使用'subject {create(:referral)}'進行記錄的方法,它使用'FactoryGirl'工廠創建一個'Referral',其中帶有'referrer'和'referrer'預先填充 – user2490003

相關問題