我想确保在用户决定发布文章时为模型设置发布日期。
我有这个:
class Article < ApplicationRecord
before_validation :check_published
validates :publish_date, presence: true, if: :article_published?
def check_published
self.publish_date = Time.now if self.published
end
def article_published?
self.published
end
end
在我的文章模型测试文件中:
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
def setup
@new_article = {
title: "Car Parks",
description: "Build new car parks",
published: true
}
end
test "Article Model: newly created article with published true should have publish date" do
article = Article.new(@new_article)
puts "article title: #{article.title}"
puts "article published: #{article.published}"
puts "article publish date: #{article.publish_date}"
assert article.publish_date != nil
end
end
测试失败。
我正在做什么,或者我需要在控制器中做这件事吗?
答案 0 :(得分:1)
article = Article.new(@new_article)
不会将文章对象保存到数据库,它只是创建一个文章对象。并且publish_date
验证没有运行。尝试设置:
article = Article.create(@new_article)