我无法理解,如何正确使用带有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
和 factories / categories.rb
FactoryGirl.define do
factory :category do
name "Category name"
permalink "category-name"
end
end
前两次测试我得到了错误:
undefined method `scan' for nil:NilClass
答案 0 :(得分: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
回调将在验证之前为永久链接提供非空值。这就是永久性验证永远不会失败的原因。