0

I want to ensure the publish date is set for model when the user decides to publish an article.

I have this:

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

In my Article model test file:

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

The test fails.

Is what I am doing possible or do I need to do it in the controller instead?

Zhang
  • 11,549
  • 7
  • 57
  • 87

1 Answers1

1

article = Article.new(@new_article) does not save the article object to database, it just creates an article object. And publish_date validation did not run. Try to set:

article = Article.create(@new_article)
Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37
  • Seems to work. So from this, it appears new() doesn't run any model validations. I was under the impression both new() and create() runs the validations. – Zhang May 29 '17 at 06:52
  • That's right. `new` does not run any of validations. You may check this SO answer https://stackoverflow.com/questions/2472393/rails-new-vs-create#2472416 about `new vs create` topic. – Ilya Lavrov May 29 '17 at 06:59