2014-04-29 18 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回调将在验证之前为永久链接提供非空白值。这就是为什么验证永久链接永远不会失败。