2017-05-29 73 views
0

我想确保在用户决定发布文章时为发布日期设置发布日期。Rails验证发布日期仅在发布时才存在

我有这样的:

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 

测试失败。

是我在做什么可能,或者我需要在控制器中做到这一点?

回答

1

article = Article.new(@new_article)不保存文章对象到数据库,它只是创建一个文章对象。并且publish_date验证没有运行。尝试设置:

article = Article.create(@new_article) 
+0

似乎工作。由此看来,new()不会运行任何模型验证。我在印象之下new()和create()运行验证。 – Zhang

+0

没错。 'new'不运行任何验证。你可以检查这个SO回答https://stackoverflow.com/questions/2472393/rails-new-vs-create#2472416关于'新vs创建'主题。 –