gpt4 book ai didi

ruby-on-rails - 如何使用 rspec with before_validation

转载 作者:行者123 更新时间:2023-12-02 01:50:02 29 4
gpt4 key购买 nike

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

模型/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

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

关于ruby-on-rails - 如何使用 rspec with before_validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358574/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com