2014-04-29 40 views
3

我不明白,如何正確使用Rspec的before_validation回調。如何使用rspec與before_validation

型號/ category.rb

class Category < ActiveRecord::Base 
    validates_presence_of :name, :permalink 
    before_validation :generate_permalink 

    private 
    def generate_permalink 
     self.permalink = Russian.translit(name).parameterize if permalink.blank? 
    end 
end 

category_spec.rb

describe Category do 
    it { should validate_presence_of(:name) } 
    it { should validate_presence_of(:permalink) } 
    it "should generate permalink" do 
     category = build(:category, name: "Category name", permalink: "") 
     category.valid? 
     category.permalink.should eq "category-name" 
    end 
end 

工廠/ categories.rb

FactoryGirl.define do 
    factory :category do 
    name "Category name" 
    permalink "category-name" 
    end 
end 

對於前兩個測試我的錯誤:

undefined method `scan' for nil:NilClass 
+0

也一樣。 **'tl; dr' **答案是:不能使用'validate_presence_of'和'before_validation'回調來設置該屬性的值。 –

回答

2

您可以檢查驗證了一個實例,而不是類本身:

it "should be invalid without a name" do 
    category = build(:category, name: "some name", permalink: "some link") 
    expect{ category.name = nil }.to change{ category.valid? }.to false 
end 

驗證永久的存在在你的代碼是過度的。 before_validation回調將在驗證之前爲永久鏈接提供非空白值。這就是爲什麼驗證永久鏈接永遠不會失敗。