2015-10-07 59 views
1

我設置了一個自定義驗證,用於在提交評論之前檢查用戶是否投票支持相冊。驗證在客戶端運行良好,但是當運行我的Rspec測試時,我似乎遇到了一些問題。使用gem特定方法運行自定義驗證

驗證使用作爲Votable寶石的voted_for?方法的行爲。不幸的是,這是事情變壞的地方。對於我的非自定義驗證(該做的工作經常BTW)我得到一個錯誤這樣的:

3) Review validations should ensure body has a length of at least 40 
    Failure/Error: it { should validate_length_of(:body).is_at_least(40) } 
    NoMethodError: 
     undefined method `voted_for' for nil:NilClass 

我需要什麼,以做要認識到這一點的方法?

審查模式

class Review < ActiveRecord::Base 
    belongs_to :album 
    belongs_to :owner, class_name: "User", foreign_key: :user_id 

    validates :body, presence: true, length: { minimum: 40 } 

    def album_vote 
    if !owner.voted_for?(album) 
     errors.add(:review, "requires an album vote before submitting") 
    end 
    end 
end 

評論廠

FactoryGirl.define do 
    factory :review do 
    body { Faker::Lorem.paragraph(2) } 

    album 
    association :owner, factory: :user 
    end 
end 

回答

0

你需要確保有實際上是一個老闆。錯誤僅僅是因爲你打電話給nil,並且與ActsAsVotable沒有任何關係。

class Review < ActiveRecord::Base 
    belongs_to :album 
    belongs_to :owner, class_name: "User", foreign_key: :user_id 
    validates :body, presence: true, length: { minimum: 40 } 
    validates :owner, presence: true 

    def album_vote 
    # consider raising an error if there is no owner. 
    if owner && !owner.voted_for(album) 
     errors.add(:review, "requires an album vote before submitting") 
    end 
    end 
end 

,然後改變你的工廠定義創建店主:

FactoryGirl.define do 
    factory :user, aliases: [:owner] do 
    # ... 
    end 
end 

FactoryGirl.define do 
    factory :review do 
    body { Faker::Lorem.paragraph(2) } 
    album 
    owner 
    end 
end 
+0

錯誤也可能關係到你如何在您的測試調用工廠。 – max

+0

是的它看起來像它需要檢查條件中的預先存在的'所有者'。謝謝Max! –