我无法理解如何正确使用 before_validation 回调与 Rspec。
模型/类别.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
类别_规格.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
and 工厂/类别.rb
FactoryGirl.define do
factory :category do
name "Category name"
permalink "category-name"
end
end
对于前两个测试,我遇到了错误:
undefined method `scan' for nil:NilClass
您可以检查实例的验证,而不是类本身的验证:
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
回调将在验证之前为永久链接提供非空值。这就是为什么永久链接的验证永远不会失败的原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)