本文介绍了如何使用 rspec with before_validation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解,如何正确使用 before_validation 回调与 Rspec.

I cannot understand, how correct use before_validation callback with Rspec.

models/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

对于前两个测试,我遇到了错误:

For first two tests I got errors:

undefined method `scan' for nil:NilClass

推荐答案

您可以检查实例的验证,而不是类本身:

You can check validation for an instance, not for the class itself:

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 回调将在验证之前为永久链接提供非空值.这就是永久链接验证永远不会失败的原因.

Validation of permalink presence in your code is excessive.The before_validation callback will provide non-blank value for the permalink before validation. That's why validation of permalink will never fail.

这篇关于如何使用 rspec with before_validation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:36