【发布时间】:2016-11-02 16:13:28
【问题描述】:
我有一个带有多个验证的链接模型。当我运行整个 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
【问题讨论】:
标签: ruby-on-rails activerecord rspec model ruby-on-rails-5