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
也一樣。 **'tl; dr' **答案是:不能使用'validate_presence_of'和'before_validation'回調來設置該屬性的值。 –