我有一个带有多个验证的链接模型。当我运行整个rspec套件时,规范在最后一次验证时失败“不应该允许无效的URL”
然而,当我运行rspec spec/models/link_spec.rb
时,模型规范通过了。永远不会调用validate_url
方法。我的rails应用程序也忽略了模型创建时的回调。
这是我的模特:
require 'uri'
class Link < ApplicationRecord
belongs_to :user
validates :url, presence: true
validates :title, presence: true
validates :read, absence: false
validates :user_id, presence: true
before_save :validate_url
private
def validate_url
require 'pry'; binding.pry
uri = URI.parse(self.url)
uri.kind_of?(URI::HTTP)
rescue URI::InvalidURIError
false
end
end
和我的模型规格:
require 'rails_helper'
describe Link, type: :model do
it { should validate_presence_of :url }
it { should validate_presence_of :title }
it { should validate_presence_of :user_id }
it "should not allow an invalid url" do
link = Link.create({
title: "new link",
url: "garbage",
user_id: 1
})
expect(link.valid?).to be_falsey
expect(link.save).to be_falsey
end
end
为什么不访问回调方法的任何想法?我在Rails 5.0.0.1和RSpec 3.5.4
上答案 0 :(得分:1)
# Create a Production record
new_manufacturing = models.execute_kw(db, uid, password,
'mrp.production', 'create',
[{'product_id':34,'product_uom':1, 'bom_id':4, 'product_qty': 1.0}],)
# Call workflow to confirm production.
models.exec_workflow(db, uid, password, "mrp.production", 'button_confirm', new_manufacturing)
# Force reserve dreictly as its not part workflow for mrp
models.execute_kw(db, uid, password, 'mrp.production', 'force_production', [new_manufacturing])
#prepare context consume product wizard.
context={'active_id': new_manufacturing, 'active_ids': [new_manufacturing], "active_model": "mrp.production"}
# Create a consume wizar object
produce_id = models.execute_kw(db, uid, password,
'mrp.product.produce', 'create',
[{'product_id':34, 'product_qty': 1.0, 'mode': 'consume_produce'}, context])
# execue Consume wizard to trigger final workflow record.
models.execute_kw(db, uid, password, 'mrp.product.produce', 'do_produce', [[produce_id], context])
方法主要用于准备数据,或在操作发生之前执行其他操作。验证需要在before_*
步骤和ActiveRecord对象中进行。因此,我会删除该代码并将其放在validation
句中。
您可以使用以下内容:
validate
或者您也可以使用validate :url_format
...
private
def url_format
uri = URI.parse(self.url)
uri.kind_of?(URI::HTTP)
rescue URI::InvalidURIError
errors.add(:url, 'Url is invalid')
end
validate
帮助:
format
我不知道为什么运行spec文件时解决方案有效。我阅读了文档,并指出在任何validate :url, format: { with: URI::regexp(%w(http https)) }
回调中返回:abort
将中止before_*
操作并返回false。
更新:返回save
并不会阻止保存记录,您需要将错误添加到错误集合中:
false